3

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.

5
  • 1
    This is possible to do, but you'd be distancing yourself from HTML5-style validation, especially since your function would have to be asynchronous to look up a database. (I'm 99% certain "pre-HTML5" JS validation frameworks are out there, so you could try any of those) Commented Dec 23, 2014 at 16:52
  • You can do it, just do and AJAX request to validate your data against the DB. Commented Dec 23, 2014 at 16:52
  • You can use jQuery to easily achieve this effect. You can use the jQuery.change() function to basically validate inputs on the fly using jQuery.ajax(), or the specific jquery.post()/jquery.get() functions. Commented Dec 23, 2014 at 16:56
  • I need to display an error message if the user enters a duplicate value. Is it possible to achieve the same UI as with HTML5 since the message is dependent on the browser? Commented Dec 23, 2014 at 17:02
  • jac0117, your question in a comment is much more specific and easily answerable (the answer is “no”). but different from the original question. Commented Dec 23, 2014 at 17:30

2 Answers 2

3

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!');
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.