Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 909
jac0117 Avatar asked Apr 22 '26 15:04

jac0117


2 Answers

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!');
        }
    });
}
like image 84
dave00000002 Avatar answered Apr 24 '26 06:04

dave00000002


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.

like image 45
Jukka K. Korpela Avatar answered Apr 24 '26 07:04

Jukka K. Korpela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!