Wednesday, July 29, 2015

Triggering HTML5 Form Validation

HTML:

<a href="#" id="validateFieldBtn">Validate a field</a>
| <a href="#" id="validateFormBtn">Validate a form</a>
<br /><br />

<form id="testForm">
    First Name: <input type="text" name="firstname" id="firstname" placeholder="Enter your name"/>
</form>

JavaScript:

$(document).ready(function () {
    $('#validateFieldBtn').on('click', function(e){
        e.preventDefault();
        
        if ($('#firstname').val() !== 'Bot') {
            // mark this field invalid by setting an error message.
            $('#firstname').get(0).setCustomValidity('Please enter a valid name');
        }
        
        // checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
        if ($('#firstname').get(0).checkValidity() != true) {
            // triggering the browser's native validation UI.
            $('#firstname').get(0).reportValidity();
        }
    });
    
    $('#validateFormBtn').on('click', function(e){
        e.preventDefault();
        
        if ($('#firstname').val() !== 'Bot') {
            $('#firstname').get(0).setCustomValidity('Please enter a valid name');
        }
        
        if ($('#testForm').get(0).checkValidity() != true) {
            $('#testForm').get(0).reportValidity();
        }
    });
});

Demo: http://jsfiddle.net/Lz17jbr5/1/

No comments: