Constraint validation API

Aniket Kambli
Udgama Blog
Published in
5 min readMar 20, 2020

The validation that is provided by using basic HTML attributes does not allow the developers to customize the message shown to the user. Yes, it can be customized using javascript but again it is a tedious task. Thus when it comes to more complex validations that need to be done which helps the user to get a perfect understanding of what the error is, we use the constraint validation API.

Note: Both basic and complex validations are provided by this API.

What is constraint validation API ?

It is an inbuilt functionality provided by JavaScript to perform complex as well as simple validation. Enough of theory lets get our hands dirty and start some coding.

Basic validations using constraint validation API:

In the above example, you can see that the user input is validated based upon the condition that the value should lie between 100 and 300. Now, this can be done with the basic html but this example shows just how easy it is to use constraint validation provided by javascript. Here’s the code.

<!DOCTYPE html>
<html>
<body>
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="100" max="300" required />
<button onclick="myFunction()">OK</button>
<p>
If the number is less than 100 or greater than 300, an error message will
be displayed.
</p>
<p id="demo"></p><script>
function myFunction() {
var inpObj = document.getElementById("id1");
inpObj.setCustomValidity(
"We have limited stock please enter value between 100 and 300"
);
inpObj.willValidate = false;
console.log(inpObj.willValidate);
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
</html>

In the above example, the function ‘myfunction()’ is called when the user submits the form. In this function, the input element is stored inside of an object called inpObj and then using this object, javascript performs further validation. We can even set the custom validity message for this object using the setCustomValidity() function.

inpObj.willValidate = false; //This is a read only property which tells us whether the given object is going to be validated or not by the javascript.

The checkValidity() function returns a boolean value indicating whether the given object has passed the particular validation condition or not and then the appropriate message is displayed to the user.

Some properties provided by the API.

In this example, we are using the different attributes provided by the validation API. Some of these include badInput, customError, patternMismatch, rangeOverflow, rangeUnderflow, stepMismatch, tooLong, tooShort, typeMismatch, valid, and valueMissing.

The above example illustrates the use of patternMismatch, rangeOverflow, rangeUnderflow. If the value falls below the min attribute of the tag then the rangeUnderflow is automatically set to true and if the value does not match the specified regular expression then the patternMismatch is set to true. Here’s the code.

<!DOCTYPE html>
<html>
<body>
<h3>Overflow condition</h3>
<input id="id1" type="number" max="100" required />
<button onclick="myFunction()">OK</button>
<h3>Underflow condition</h3>
<input id="id2" type="number" min="100" required />
<button onclick="myFunction()">OK</button>
<h3 for="country_code">Country code:</h3>
<input type="text" id="id3" name="country_code" pattern="[A-Za-z]{3}" />
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction() {
var txt = "";
var txt1 = " ";
var txt2 = " ";
console.log("Overflow", document.getElementById("id1").validity.valid);
console.log("Underflow", document.getElementById("id2").validity.valid);
if (document.getElementById("id1").validity.rangeOverflow) {
txt = "Value too large";
}
if (document.getElementById("id2").validity.rangeUnderflow) {
txt1 = "Value too small";
}
if (document.getElementById("id3").validity.patternMismatch) {
txt2 = "Enter country code of 3 letters";
}
document.getElementById("demo").innerHTML = txt;
document.getElementById("demo2").innerHTML = txt1;
document.getElementById("demo3").innerHTML = txt2;
}
</script>
</body>
</html>

In the above example, there are 3 input fields, each has their own button and on the click of it the function is called which does the validation and then the appropriate message is displayed to the user.

Complex validation using constraint validation API:

As we know that each and every country has its own country code with each one having some specific format , then in this case, doing validation using basic html would be tough and it would be very much simpler if we use the following code.

<!DOCTYPE html>
<html>
<body>
<p>Enter a number and click OK:</p>
<form>
<label for="ZIP">ZIP : </label>
<input type="text" id="ZIP">
<label for="Country">Country : </label>
<select id="Country">
<option value="ch">Switzerland</option>
<option value="fr">France</option>
<option value="de">Germany</option>
<option value="nl">The Netherlands</option>
</select>
<input type="submit" value="Validate">
</form>
<script>
window.onload = function () {
document.getElementById("Country").onchange = checkZIP;
document.getElementById("ZIP").oninput = checkZIP;
}
function checkZIP() {

var constraints = {
ch : [ '^(CH-)?\\d{4}$', "Switzerland code must have exactly 4 digits" ],
fr : [ '^(F-)?\\d{5}$' , "France must have 5 digits" ],
de : [ '^(D-)?\\d{5}$' , "Germany zip code must have 5 digits],
nl : [ '^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$',
"Netherlands code must have "
};

var country = document.getElementById("Country").value;
// Get the NPA field
var ZIPField = document.getElementById("ZIP");

var constraint = new RegExp(constraints[country][0], "");
console.log(constraint);

if (constraint.test(ZIPField.value)) {
tell it
ZIPField.setCustomValidity("");
}
else {

ZIPField.setCustomValidity(constraints[country][1]);
}
}</script>
</body>
</html>

In this, there are different countries and their country code is specified using the regular expression. If any of the input field’s value does not match the criteria provided in the regular expression then the patternMismatch is set to true and then the customised messages are displayed to the user accordingly.

Conclusion:

You can use whatever you are comfortable with for doing your client side validation. Constraint validation API just makes it simple and is an effective way to communicate with the user through errors 😉

--

--