JavaScript Form Verification and javascript Form Verification
JavaScript Form Verification
JavaScript can be used to verify the input data in the HTML form before the data is sent to the server.
JavaScript is often used to verify the correctness of form data:
- Is the verification form data empty?
- Verify that the entered email address is correct?
- Is the verification date entered correctly?
- Verify whether the input content of the form is Numeric?
Required (or required) project
The following function is used to check whether the user has entered a required (or required) project in the form. If required or required, the warning box is displayed, and the return value of the function is false. Otherwise, the return value of the function is true (meaning there is no data problem ):
Function validateForm ()
{
Var x = document. forms ["myForm"] ["fname"]. value;
If (x = null | x = "")
{
Alert ("First name must be filled out ");
Return false;
}
}
The preceding functions are called when the form is submitted:
Instance
<Form name = "myForm" action = "demo_form.asp" onsubmit = "return validateForm ()" method = "post">
First name: <input type = "text" name = "fname">
<Input type = "submit" value = "Submit">
</Form>
Email Verification
The following function checks whether the input data conforms to the basic syntax of the email address.
That is to say, the input data must contain the @ symbol and the dot (.). At the same time, @ cannot be the first character of the email address, and @ must have at least one dot:
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 complete code of the HTML form is as follows:
Instance
<Form name = "myForm" action = "demo_form.asp" onsubmit = "return validateForm ();" method = "post">
Email: <input type = "text" name = "email">
<Input type = "submit" value = "Submit">
</Form>