HTML Form Validations

In this topic, you will learn how to validate the HTML forms using JavaScript.

Below JavaScript example shows how we can prevent form from being submitted. The form element has an attribute called as “post” which is used to send the HTTP POST request to the server. To prevent the invalid data from being sent to the server, we need to validate the form. We are calling checkForm() function just before submitting the form. “checkForm()” function will check if all fields in HTML form have valid data. If validation is successful, it will return true and form will be submitted successfully. If validation is not successful, it will return false and form will not be submitted.

function checkForm() {
var num = document.getElementById(“number”).value;
if (num == “”) {
console.log(“Number can not be empty”);
return false;
}
}

<form name=”simple” action=”abc.php” onsubmit=”return checkForm()” method=”post”>
<input type=”text” id=”number”>
<input type=”submit” value=”Submit”>
</form>

Validation Attributes in HTML
We can add these validation attributes for HTML element.

  1. required – When HTML element has this attribute, it means that it is mandatory to fill the data for this field.
  2. disabled – This attribute means that field should be disabled.
  3. max and min – These attributes can be used to set range of the value for specific field.

Consider below HTML snippet. Here we have added attributes min, max and  required. It means that age field should be filled with number between 1 and 130.
<input id=”age” type=”number” min=”1″ max=”130″ required>

Below JavaScript code shows how to validate this field. Note that we have used “checkValidity()” function and if it returns true, we are displaying validation message on the page.

var ageObject = document.getElementById(“age”);

if (ageObject .checkValidity() == false) {

console.log(“age validation was not successful.” + ageObject.validationMessage);

}

You may also like...