from onsubmit form validation before submitting

Form's onsubmit event--the best way to implement validation before form submission

The form should also have a pre-submit event, which is onsubmit. The function of this event is to automatically execute the specified things before the form is submitted.

js method:

copy code
 1 function check(){
 2    var name = document.getElementById("name").value;
 3    if(name ==  null || name == ''){
 4         alert("用户名不能为空");
 5         return false;
 6    }
 7    return true;
 8 }
 9 
10 <form name="form" action="跳转的页面" method="post"  onsubmit="return check()">
11   <input type="text" id="name"/>
12   <input type="sumit" value="提交"/>
13 </form>
copy code


It should be noted that the return in onsubmit="return check()" must be added, otherwise, even if the return value of check is false, it will still be submitted. That is to say, onsubmit="return false" means no submission; onsubmit="return true" or onsubmit="return" both perform submission.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326258225&siteId=291194637