Validating is making sure you have the right data for the right input. We wouldn’t want a phone number put into an input expecting email. Mostly, HTML is not used to validate the input but there are a couple of easy checks to see if our data is right. The first is with the required attribute.
The required attribute is different from other attributes in that it doesn’t have an equals sign. There is no required=”something”. All you have to do is type required in an input tag. In the following code, I’m using the login.html file that we made in the last post and made the username input required.
Now if we try to login without putting in a username we get the following:
Of course, we’ll want the password to also be required:
Trying to login with just a username gives us this:
Only when all the required inputs have been filled in will our form send the data to, in this case, Google.
When we want an e-mail address to be input, we can make sure that the data is in the form of an e-mail address. Let’s try this by changing our username input into an e-mail input. While we’re at it, let’s change the <label> tag and placeholder attribute to “E-Mail” also.
If we try our form now we find that it will only allow us to input an e-mail address. Just typing in USER or user@ returns us:
Next post we’ll take a look at a few of the other types of inputs.
Attributes To Remember