JavaScript form validation
JavaScript Form Validation
JavaScript Form Validation
JavaScript available to validate the input data in the HTML form before the data is sent to the server.
Form data often requires the use of JavaScript to verify its correctness:
Verify whether the form data is empty?
Verify whether the input is a correct email address?
Verify whether the date is entered correctly?
Verify whether the form input content is numeric?
Required (or required) items
The following function is used to check whether the user has filled in the required (or required) items in the form. If the required field or required field is empty, the warning box will pop up and the return value of the function is false. Otherwise, the return value of the function is true (meaning there is no problem with the data):
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert ("Last name must be filled in");
return false;
}
}
The above function is called when the form is submitted:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <head> <script> function validateForm(){ var x=document.forms["myForm"]["fname"].value; if (x==null || x==""){ alert("姓必须填写"); return false; } } </script> </head> <body> <form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post"> 姓: <input type="text" name="fname"> <input type="submit" value="提交"> </form> </body> </html>
E-mail Validation
The following function checks whether the entered data conforms to the basic syntax of an email address.
This means that the input data must contain the @ symbol and the period (.). At the same time, @ cannot be the first character of the email address, and there must be at least one period after @:
function validateForm(){
var x=document.forms["myForm"]["email "].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
alert("Not a valid e-mail address");
return false;
}
}
The following is the complete code along with the HTML form:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <head> <script> function validateForm(){ var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){ alert("不是一个有效的 e-mail 地址"); return false; } } </script> </head> <body> <form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="提交"> </form> </body> </html>