DawnPaladin
DawnPaladin

Reputation: 1533

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?

Upvotes: 1

Views: 28

Answers (1)

DawnPaladin
DawnPaladin

Reputation: 1533

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.");
    }
}

Upvotes: 1

Related Questions