JavaScript form validation
JavaScript form validation
JavaScript can be used before being sent to the server in the data on these HTML form input data validation.
Form data often need to use JavaScript to verify its correctness:
- Verify that the form data is empty?
- Verify whether the input is a correct email address?
- Verify the date entered correctly?
- Validate form input is numeric type?
Required (or mandatory) project
The following functions are used to check whether the user is required to fill in a form (or mandatory) project. If required or necessary option is empty, then a warning box will pop up, and the function's return value is false, otherwise the function's return value was true (no problem means that the data):
function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("姓必须填写"); return false; } }
The above function is called when the form is submitted form:
Examples
姓: <input type="text" name="fname">
<input type="submit" value="提交">
</form>
try it"
E-mail verification
Function checks whether the data entered meets the following basic syntax of email address.
His point is that the input data must include the @ symbol and the dot (.). Meanwhile, the @ is not the first character mail address after the @ and the need for at least a number of points:
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; } }
The following is the complete code along with HTML form:
Examples
Email: <input type="text" name="email">
<input type="submit" value="提交">
</form>
try it"