HTML5 has a pretty convenience input validation feature which makes form and input validation much more easier.
Basic
You must have seen something like this:
This can easily done by adding a required attribute to the input tag, when submitting without filling out the required field, a default message like above will pop up.
<form>
<input type="text" required />
<button type="submit">Submit</button>
</form>
What if I need write my own failed message instead of “Please fill out this field”?
Custom message
We need to use some Javascript to do the trick.
Let’s say the following is my HTML form:
<form>
<input type="email" id="1" />
<input type="text" id="2" />
<button type="submit" onclick="check(document.getElementById('2'))">
submit
</button>
</form>
Then the following Javascript will add custom validation message of “Email must be matching” when two inputs are not matching.
function check(input) {
if (input.value !== document.getElementById('1').value) {
input.setCustomValidity('Email must be matching.');
} else {
input.setCustomValidity('');
}
}
It is important to keep in mind that you need to set validity back to empty string after it pass the validation.
Custom styling
Now it’s time to add some ‘fancy’ style to my input! Hmmmmm… I like my input to be in red border when invalid. I can do it using either CSS or Javascript
CSS approach
This is all I need:
input:invalid {
border: 1px solid red;
}
View at JSFIDDLE
pretty easy, right?
What is the problem with this approach? If my validation constrain is ‘required’, the input will be in red border even before I enter anything into it. In other words, it is invalid since rendered.
JS approach
This might be a little more complicated than the CSS approach since I have to take care of the validation by myself.
I need to change my HTML code a little bit so that I can restore the border styles on input:
<form>
<input type="email" id="1" oninput="restore(this);" />
<br />
<input type="text" id="2" oninput="restore(this);" />
<br />
<button type="submit" onclick="check(document.getElementById('2'));">
submit
</button>
</form>
Here is my Javascript:
// validations
function check(input) {
if (!validateEmail(document.getElementById('1').value)) {
document.getElementById('1').style.border = 'solid 1px red';
return false;
} else if (document.getElementById('1').value !== input.value) {
input.setCustomValidity('Email Must be Matching.');
input.style.border = 'solid 1px red';
} else {
input.setCustomValidity('');
}
}
// restore border styles of input
function restore(input) {
input.style.border = 'solid 1px #aaa';
}
// return true if email is valid
function validateEmail(email) {
var re = /\S+@\S+/;
return re.test(email);
}
View at JSFIDDLE
Conclusion
I would definitely go with the CSS approach unless I have to deal with required input. Which way do you prefer?