简体   繁体   中英

Adding onto browsers' built-in form validation

I'm creating an email form for our website. I built the form using HTML5 and CSS to take advantage of browsers' built-in validation (using this shim to avoid compatibility problems). Now I want to add a "confirm your email address" field, which shouldn't be marked valid unless it matches the "enter your email address" field.

I've written some JavaScript to compare the two fields. Is there a way for JavaScript to mark a field as valid/invalid for the browser's built-in validation? Or do I need to switch to a third-party validation plugin to get this feature?

Found the answer right after I posted the question. You call <element>.setCustomValidity() on the field, passing in an empty string to set the field as valid. If it's not valid, you instead pass in a string with the reason why.

Here's my code:

$('#emailConfirmation').on('keyup', function() {
    if ($('#emailConfirmation').val() == $('#email').val()) {
        $("#emailConfirmation")[0].setCustomValidity("");
    } else {
        $("#emailConfirmation")[0].setCustomValidity("Check that you've typed your email address the same way in both places.");
    }
});

Here it is again without jQuery:

document.getElementById('emailConfirmation').onchange = function() {
    if (document.getElementById("emailConfirmation").value == document.getElementById("email").value) {
        document.getElementById("emailConfirmation").setCustomValidity("");
    } else {
        document.getElementById("emailConfirmation").setCustomValidity("Check that you've typed your email address the same way in both places.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM