简体   繁体   English

在onsubmit内部未调用JS表单验证功能

[英]JS form validation function is not called inside onsubmit

I am trying to run a form validation on an HTML form with pureJS. 我正在尝试使用pureJS在HTML表单上运行表单验证。

Here is my code: 这是我的代码:

<form name="myForm" action="" onsubmit="alert('hello world');return validateForm(myForm);">
<label>
    <input name="username" placeholder="Name" type="text" required>
</label>
<label>
    <input name="email" placeholder="Email" type="email" required>
</label>
<input type="submit" value="Submit 1">
<button type="submit">Submit 2</button>
<button>Submit 3</button>

function validateForm(formName) {
  const form = document.forms[formName];
  for(let i = 0; i < form.elements.length; i++){
    const element = form.elements[i];

    // validation fails if element is required and blank
    if(element.attributes["required"] && !element.value.length){
        element.focus();
        return false;
    }

    // validation fails if email is not valid
    if(element.getAttribute('type') === "email" && !validateEmail(element.value)) {
        element.focus();
        return false;
    }
  };

  return true;
}

function validateEmail(str) {
    var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*/;
    return regexp.test(str);
}

new link without typo: http://jsfiddle.net/mech8bon/ 没有错字的新链接: http : //jsfiddle.net/mech8bon/

http://jsfiddle.net/4bjmh9as/ http://jsfiddle.net/4bjmh9as/

Expected: to call the alert then the function. 预期:然后调用警报。

Result: nothing called at all. 结果:什么都没有。

Open the developer tools in your browser. 在浏览器中打开开发人员工具。 Look at the console. 查看控制台。 Read the error message. 阅读错误消息。

Uncaught TypeError: Cannot read property 'elements' of undefined 未捕获的TypeError:无法读取未定义的属性“元素”


You are passing the variable myForm : 您正在传递变量 myForm

 validateForm(myForm); 

But then you are treating it as a string containing a property name: 但是随后您将其视为包含属性名称的字符串:

 const form = document.forms[formName]; 

String literals need quotes around them: 字符串文字需要用引号引起来:

validateForm('myForm');

The solution thanks to Ric and Quentin in this fiddle: http://jsfiddle.net/eg89b02j/2/ 感谢Ric和Quentin提出的解决方案: http : //jsfiddle.net/eg89b02j/2/

<form name="myForm" action="" onsubmit="return validateForm(this);" novalidate>

The first fix was adding novalidate attribute to the form tag. 第一个解决方法是将novalidate属性添加到form标签。

The second fix was making the form more generic by sending the form itself instead of name. 第二个解决方法是通过发送表单本身而不是名称来使表单更加通用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM