JavaScript Forms

JavaScript form validation

JavaScript can be used to validate these input data in HTML forms before the data is sent to the server.

Form data often requires JavaScript to verify its correctness:

  • Verify that the form data is empty?
  • Verify that the input is a correct email address?
  • Is the verification date entered correctly?
  • Verify that the form input is numeric?

Required (or required) items

The following function checks if the user has filled in the required (or required) items in the form. If the required or required options are empty, a warning box will pop up, and the return value of the function will be false, otherwise the return value of the function will be true (meaning there is no problem with the data):

JavaScript Example

function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("Surname must be filled"); return false; } }

The above function is called when the form is submitted:

HTML Form Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
Try it Yourself »

E-mail verification

The following function checks if the data entered matches the basic syntax of an email address.

This means that the data entered must include the @ sign and a period (.). Also, @ cannot be the first character of the email address, and at least one dot is required after @:

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; } }