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

前端 未结 3 1301
余生分开走
余生分开走 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: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

提交回复
热议问题