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.
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!');
}
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With