The typical form data validated by JavaScript are as follows:
1. Has the user filled in the required items in the form?
2. Is the email address entered by the user legal?
3. Has the user entered a legal date?
4. Did the user enter text in the numeric field?
Here is the username and password verification code:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> function validateForm() { var username = document.forms["myForm"]["username"].value; var password = document.forms["myForm"]["password"].value; alert(username+" "+password); } </script> </head> <body> <form name="myForm" action="" onSubmit=" return validateForm()" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> </body> </html>
Required (or required) item verification:
The following function is used to check whether the user has filled in the required (or required) items in the form. If required or the required field is empty, a 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 validate_required(field,alerttxt) { with (field) { if (value==null||value=="") {alert(alerttxt);return false} else {return true} } }
Here is the code along with the HTML form:
<html> <head> <script type="text/javascript"> function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") {alert(alerttxt);return false} else {return true} } } function validate_form(thisform) { with (thisform) { if (validate_required(email,"Email must be filled out!")==false) {email.focus();return false} } } </script> </head> <body> <form action="submitpage.htm" onsubmit="return validate_form(this)" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>
E-mail verification
The function below 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 validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@") dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) {alert(alerttxt);return false} else {return true} } }
Here is the complete code along with the HTML form:
The above code is the user name, password, required fields, required options and email, as well as the code of the form. I hope it will be helpful for everyone to learn javascript form verification.