简体   繁体   中英

Javascript fallback for the HTML5 “pattern” attribute on <input>

I'm using the HTML5 "pattern" attribute for client side validation (please don't tell me about server-side validation, I have that). I want to use a Javascript or jQuery fallback for users using browsers without "pattern" support. What's a good way to do that?

Here's an example input element:

<input type=tel name=contact[phone] id=phone required pattern=^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$>

On the submit event of your form (or wherever), validate it using its existing pattern property.

var input = document.getElementsByName('contact[phone]')[0],
    isValid = input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0;

jsFiddle .

You will want to check browser compatibility first to see if it supports the pattern attribute. You can do that with Modernizr .

You can use Modernizr to check to see what's supported by the user's browser.

Detecting HTML5 with Modernizr

Modernizer lets you do stuff like this:

if (Modernizr.canvas) {
  // let's draw some shapes!
} else {
  // no native canvas support available :(
}

My best guess would be first having a function that uses jQuery to find the browser and version, and match that up to if it supports pattern or not, and then do something like

 $("#element").onChange(function() { if(doesNotSupportPattern()) { var pattern = $(this).prop('pattern'); if(!$(this).val().match(pattern))) { //Code to make form invalid } } }); 

Or something of the like


Change of plan, this isn't the way to go

$("#form").submit(function()
{
    var valid = true;
    $(this).find('input').each(function()
    {
        if(!$(this).prop('pattern'))
            continue;

        if(!$(this).val().match($(this).prop('pattern')))
            valid = false;
    });

    if(!valid)
    {
        //invalidate form
    }
});

Would be better off. This way it'll trigger for each element, and it's more compact, and if pattern is enabled, it'll not interfere anyway, as it should only submit if it all matches, and if it doesn't, the form is invalidated anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM