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

前端 未结 3 1292
余生分开走
余生分开走 2020-12-18 03:12

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

相关标签:
3条回答
  • 2020-12-18 03:50

    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.

    0 讨论(0)
  • 2020-12-18 03:56

    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

    0 讨论(0)
  • 2020-12-18 04:08

    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 :(
    }
    
    0 讨论(0)
提交回复
热议问题