JavaScript Form Validation
JavaScript Form Validation
JavaScript can be used to validate input data in HTML forms before the data is sent to the server.
Form data often requires validation using JavaScript for correctness:
Is the form data empty?
Is the input a valid email address?
Is the date entered correctly?
Is the form input numeric?
Required Fields
The following function checks if the user has filled out the required fields in the form. If any required field is empty, an alert box pops up and the function returns false; otherwise, it returns true (indicating no issues with the data):
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Last name must be filled out");
return false;
}
}
This 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>
Email Validation
The following function checks if the input data matches the basic syntax of an email address.
This means the input must include 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("Not a valid e-mail address");
return false;
}
}
Here is the complete code including 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>