JavaScript Form Validation

Form validation is the process of ensuring that the data entered by users meets the expected format and rules.

In web development, form validation is commonly used to check the validity of user input, such as email addresses, passwords, phone numbers, etc.

Through form validation, invalid data can be prevented from being submitted to the server, thereby improving data accuracy and security.


JavaScript Form Validation

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

Form data often needs to be validated using JavaScript for correctness:

  • Validate whether the form data is empty?
  • Validate whether the input is a correct email address?
  • Validate whether the date is entered correctly?
  • Validate whether the form input content is numeric?

Why is Form Validation Needed?

  1. Data Accuracy: Ensures that the data entered by users meets the expected format, avoiding invalid data.
  2. Security: Prevents malicious users from submitting harmful data, such as SQL injection, cross-site scripting (XSS) attacks, etc.
  3. User Experience: Provides timely feedback on user input errors, helping users quickly correct problems.

Basic Methods of JavaScript Form Validation

JavaScript provides multiple methods to implement form validation. The following are several common approaches:

1. Using HTML5 Built-in Validation

HTML5 provides some built-in form validation features, such asrequired、pattern、min、maxand other attributes. These attributes can simply implement basic form validation.

Example

<form>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <input type="submit" value="Submit">
</form>

In the above example,requiredthe attribute ensures that the user must enter an email address, andtype="email"automatically validates whether the input is in a valid email format.

2. Using JavaScript Custom Validation

The following function is used to check whether the user has filled in the required (or mandatory) items in the form. If the required items are empty, an alert box will pop up, and the function will return false; otherwise, the function will return true (meaning there are no problems with the data):

function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("Last name is required"); return false; } }

The above function is called when the form is submitted:

Example

<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">Last name:<input type="text" name="fname"> <input type="submit" value="Submit"> </form>

Try it Yourself »


E-mail Validation

The following function checks whether the entered data conforms to the basic syntax of an email address.

This means that the entered data must contain an @ symbol and a dot (.). Also, @ cannot be the first character of the email address, and there must be at least one dot after the @:

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("is not a valid e-mail address"); return false; } }

The following is the complete code along with the HTML form:

Example

<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form>

Try it Yourself »

Using Regular Expressions for Validation

Regular Expression is a powerful tool that can be used to match complex string patterns.

The following is an example of using a regular expression to validate an email address:

Example

function validateEmail(email) {
  var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

var email = "[email protected]";
if (validateEmail(email)) {
  console.log('Valid email address.');
} else {
  console.log('Invalid email address.');
}

Try it Yourself »

In this example, we define a regular expression to validate the format of the email address. If the entered email address meets the format requirements, the function will returntrue, otherwise it will returnfalse。

Other Extensions