JavaScript can be used to validate these input data in HTML forms 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 that the input is a correct email address?
Verify that the date is entered correctly?
Verify whether the form input content is numeric?
Required (or required) items
Following functions Used to check whether the user has filled in the required (or required) items in the form. If it is required or the required field is empty, then 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):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </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="" onsubmit="return validateForm()" method="post"> 姓: <input type="text" name="fname"> <input type="submit" value="提交"> </form> </body> </html>
Run the program and try it out
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 @:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </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="" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="提交"> </form> </body> </html>
Run the program and try it