JavaScript can be used to validate input data in HTML forms before the data is sent to the server.
Typical form data validated by JavaScript are:
Has the user filled in the required fields in the form?
Is the email address entered by the user legal?
Has the user entered a valid date?
Did the user enter text in the numeric field?
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 the 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 validate_required(field,alerttxt) { with (field) { if (value==null||value=="") {alert(alerttxt);return false} else {return true} } }
E-mail verification (verify email address)
The following function checks whether the entered data conforms to the basic syntax of the email address.
It 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} } }
Example:
The above is the entire content of this chapter, and more For more related tutorials, please visit JavaScript Video Tutorial!