Form Validation With HTML5 and JavaScript

John Au-Yeung - Feb 2 '20 - - Dev Community

Subscribe to my email list now at http://jauyeung.net/subscribe/

Follow me on Twitter at https://twitter.com/AuMayeung

Many more articles at https://medium.com/@hohanga

Even more articles at http://thewebdev.info/

Form validation is part of browser-side HTML and JavaScript. We can use it to validate form inputs before sending the data to the server. However, we should trust the content that’s being sent, so the final validation should still be on the server.

With HTML5, form validation is a built-in feature. There are various validation attributes that come with HTML5.

When form input is valid, the :valid CSS pseudoclass is applied to the element. If it’s invalid, then the :invalid CSS pseudoclass is applied to the element.

When the form has invalid inputs, then the browser will block the form from being submitted and display an error message.


Form Validation Attributes

Pattern

The pattern attribute is available for input elements with type text, search, url, tel, email, and password.

  • It lets us set a regular expression as the value and the browser will validate it against it.

Min

This attribute applies to range, number, date, month, week, datetime, datetime-local, and time inputs.

  • When it’s applied to a range or number input, it’ll check if the inputted number is the value of the min attribute or higher.
  • When it’s applied to the date, month, or week element, then it’ll check if the date is greater than or equal to the one given in the value of this attribute.
  • For the datetime, datetime-local, time type inputs, both the date and time are checked to see if it’s greater than or equal to the one given in the value of the min attribute.

Max

The max attribute is the opposite of the min attribute. It checks if something entered is less than or equal to what’s given in the value of this attribute.

  • When it’s applied to a range or number input, it’ll check if the inputted number is the value of the min attribute or lower.
  • When it’s applied to the date, month, or week element, then it’ll check if the date is less than or equal to the one given in the value of this attribute.
  • For the datetime, datetime-local, time type inputs, both the date and time are checked to see if it’s less than or equal to the one given in the value of the min attribute.

Required

The required attribute checks if the input value is entered by the user.

  • It’s available to text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file, and also on the <select> and <textarea> elements.

Step

The step attribute checks if the input is an integer.

  • If it’s applied to an input element with the type date, then it checks for an integer number of days.
  • If it’s applied to an input element with the type month, then it checks for an integer number of months.
  • If it’s applied to an input element with the type week, then it checks for an integer number of weeks.
  • If it’s applied to an input element with the type datetime, datetime-local, time, then it checks for an integer number of seconds.
  • If it’s applied to an input element with the type range, number, then it checks for an integer.

Minlength

The minlength attribute is available to the input with types text, search, url, tel, email, password. It’s also available on the textarea element.

  • It checks for a greater than or equal to the number of characters of text that the user entered.

Maxlength

The maxlength attribute is available to the input with types text, search, url, tel, email, password. It’s also available on the textarea element.

  • It checks for a less than or equal to the number of characters of text that the user entered.

Using Form Validation Attributes

We can use form validation attributes by adding them to the element. For example, we can write a form that accepts an email address as input.

First, we write the HTML as follows:

<form id='form'>
  <label for="email">What's your email address?</label>
  <input id="email" name="email" required pattern="[^@]+@[^\.]+\..+">
  <button type='submit'>Submit</button>
</form>

In the code above, we have the input element with the required attribute, which sets the input as required.

We also added the pattern attribute with the regular expression for an email address as the value. It checks for characters before and after the at sign and periods.

Next, we add the CSS for changing the border of the input element when the input is valid or invalid as follows:

input:invalid {
  border: 1px solid red
}
input:vvalid {
  border: 1px solid black
}

We used the pseudoclasses that we mentioned at the beginning of the article to do this.

Finally, we add JavaScript code to prevent form submission for this example by calling preventDefault:

const form = document.querySelector('#form');  
form.onsubmit = (e) => {  
  e.preventDefault();  
}

Another example would be to check the length of our inputs and range. For example, we can write the following HTML to get the name and age of the user:

<form id='form'>
  <label for="name">What's your name?</label>
  <input id="name" name="name" required minlength='5' maxlength='20'>
  <br>
  <span id='name-too-short' hidden>Name is too short</span>
  <span id='name-too-long' hidden>Name is too long</span>
  <br>
  <label for="age">What's your age?</label>
  <input id="age" name="age" type='number' required min='0' max='150'>
  <br>
  <span id='age-too-high' hidden>Age is too high</span>
  <span id='age-too-low' hidden>Age is too low</span>
  <br>
  <button type='submit'>Submit</button>
</form>

We have the input elements with the length and range attributes for the name and age respectively. Also, we have the input messages and we can see them when the inputs are invalid in a way that’s described in the messages.

Again, we have the same CSS as in the first example for changing the border of the input box when the inputs are valid or invalid:

input:invalid {
  border: 1px solid red
}
input:vvalid {
  border: 1px solid black
}

Finally, we have the JavaScript for displaying the validation messages when the input is invalid:

const form = document.querySelector('#form');
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const nameTooShort = document.querySelector('#name-too-short');
const nameTooLong = document.querySelector('#name-too-long');
const ageTooLow = document.querySelector('#age-too-low');
const ageTooHigh = document.querySelector('#age-too-high');
form.onsubmit = (e) => {
  e.preventDefault();
}
name.oninput = (e) => {
  nameTooShort.hidden = true;
  nameTooLong.hidden = true;
  if (e.srcElement.validity.tooShort) {
    nameTooShort.hidden = false;
  }
if (e.srcElement.validity.tooLong) {
    nameTooLong.hidden = false;
  }
}
age.oninput = (e) => {
  ageTooLow.hidden = true;
  ageTooHigh.hidden = true;
  if (e.srcElement.validity.rangeOverflow) {
    ageTooHigh.hidden = false;
  }
if (e.srcElement.validity.rangeUnderflow) {
    ageTooLow.hidden = false;
  }
}

In the code above, we set the oninput event handler to an event handler function to check for input validity whenever something is being entered.

Inside each function, we first hide all the messages so that we don’t see the outdated ones and then check for tooShort or tooLong for the name input since we specified the min and max lengths.

If any of those errors occurred, we unhide the corresponding message element in the HTML.

Likewise, we check for rangeOverflow or rangeUnderflow for the age input since we specified the min and max lengths. If any of those errors occurred, we unhide the corresponding message element in the HTML.

With HTML5 and JavaScript, we can check for all kinds of input values for validity. We don’t have to use any libraries to do this.

Some things we can check for including length, range, any pattern with regular expressions, and so on. However, we should also check on the server-side before saving since users can still hack the browser side app to skip validation.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .