jac0117
jac0117

Reputation: 77

HTML5 input validation with function rather than pattern

I have a form where some inputs like email get validated with a regex in HTML5. I need to validate other inputs where I cannot use a pattern. I need to look into a database and look for duplicates. Can I validate by calling some function rather than using pattern?

I could validate as the user types something by calling some function, but my end goal is to achieve UI consistency. Because the email input is validated using pattern and a regex, the UI is created by the browser, so I wan the same UI when validating other fields where I cannot use regex.

Upvotes: 3

Views: 2591

Answers (2)

dave00000002
dave00000002

Reputation: 46

Yes, this is possible! With setCustomValidity.

You just need to get your input element (either through a callback, or document.getElementBy...) and call

element.setCustomValidity('message here')

If the input is valid, you can call

element.setCustomValidity('')

to clear the error message.

For example:

<input name='email' onchange='checkEmail(this)'></input>

then define checkEmail...

function checkEmail(element) {
    ajaxCallToServer(element.value, function callback(hypotheticalResponse) {
        if (hypotheticalResponse.isOk) {
            element.setCustomValidity('');
        } else {
            element.setCustomValidity('Sorry that email is already taken!');
        }
    });
}

Upvotes: 3

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201548

No, HTML5 validation has no function concept. It is in principle language-agnostic and does not even postulate JavaScript support in the browser. It supports only the checks described in HTML5 specs.

Upvotes: 1

Related Questions