Skip to content
Advertisements

Javascript Validation API

Normally, we can set the conditions using if and else.But there’s an easier way.(less code)

checkValidity()Returns true if an input element contains valid data.
setCustomValidity()Sets the validationMessage property of an input element.
<div class="container">
        <div class="form">
            <input type="number" id="number" name="number" max="7" min="3" required />
            <button type="button" onclick="ValidityForm();">Click</button>
            <p id="resultFalse" style="display:none;"></p>
            <p id="resultTrue" style="display:none;"></p>
        </div>
    </div>

    <script>
        function ValidityForm() {
            var valueInput, resultFalse, resultTrue, message;
            valueInput = document.getElementById("number");
            resultFalse = document.getElementById("resultFalse");
            resultTrue = document.getElementById("resultTrue");

            if (valueInput.checkValidity() == false) {
                resultFalse.style.display = "block";
                resultTrue.style.display = "none";
                resultFalse.innerHTML = valueInput.validationMessage;
            } else {
                resultFalse.style.display = "none";
                resultTrue.style.display = "block";
                resultTrue.innerHTML = "no error"
            }
        }
    </script>

rangeOverflowSet to true, if an element’s value is greater than its max attribute.
validity Contains boolean properties related to the validity of an input element.
if (valueInput.validity.rangeOverflow) {
                resultFalse.style.display = "block";
                resultTrue.style.display = "none";
                resultFalse.innerHTML = valueInput.validationMessage;
            }
rangeOverflow
rangeOverflow

rangeUnderflowSet to true, if an element’s value is less than its min attribute.
if (valueInput.validity.rangeUnderflow) {
                resultFalse.style.display = "block";
                resultTrue.style.display = "none";
                resultFalse.innerHTML = valueInput.validationMessage;
            }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: