How to validate pattern matching in textarea?

南楼画角 提交于 2019-11-30 06:45:14

问题


When I use textarea.checkValidity() or textarea.validity.valid in javascript with an invalid value both of those always return true, what am I doing wrong?

<textarea name="test" pattern="[a-z]{1,30}(,[a-z]{1,30})*" id="test"></textarea>​

jQuery('#test').on('keyup', function() {
    jQuery(this).parent().append('<p>' + this.checkValidity() + ' ' +
    this.validity.patternMismatch + '</p>');
});

http://jsfiddle.net/Riesling/jbtRU/9/


回答1:


HTML5 <textarea> element does not support the pattern attribute.

See the MDN doc for allowed <textarea> attributes.

You may need to define this functionality yourself.

Or follow the traditional HTML 4 practice of defining a JavaScript/jQuery function to do this.




回答2:


You can implement this yourself with setCustomValidity(). This way, this.checkValidity() will reply whatever rule you want to apply to your element. I don't think this.validity.patternMismatch can set manually, but you could use your own property instead, if needed.

http://jsfiddle.net/yanndinendal/jbtRU/22/

$('#test').keyup(validateTextarea);

function validateTextarea() {
    var errorMsg = "Please match the format requested.";
    var textarea = this;
    var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
    // check each line of text
    $.each($(this).val().split("\n"), function () {
        // check if the line matches the pattern
        var hasError = !this.match(pattern);
        if (typeof textarea.setCustomValidity === 'function') {
            textarea.setCustomValidity(hasError ? errorMsg : '');
        } else {
            // Not supported by the browser, fallback to manual error display...
            $(textarea).toggleClass('error', !!hasError);
            $(textarea).toggleClass('ok', !hasError);
            if (hasError) {
                $(textarea).attr('title', errorMsg);
            } else {
                $(textarea).removeAttr('title');
            }
        }
        return !hasError;
    });
}



回答3:


This will enable the pattern attribute on all textareas in the DOM and trigger the Html5 validation. It also takes into account patterns that have the ^ or $ operators and does a global match using the g Regex flag:

$( document ).ready( function() {
    var errorMessage = "Please match the requested format.";

    $( this ).find( "textarea" ).on( "input change propertychange", function() {

        var pattern = $( this ).attr( "pattern" );

        if(typeof pattern !== typeof undefined && pattern !== false)
        {
            var patternRegex = new RegExp( "^" + pattern.replace(/^\^|\$$/g, '') + "$", "g" );

            hasError = !$( this ).val().match( patternRegex );

            if ( typeof this.setCustomValidity === "function") 
            {
                this.setCustomValidity( hasError ? errorMessage : "" );
            } 
            else 
            {
                $( this ).toggleClass( "error", !!hasError );
                $( this ).toggleClass( "ok", !hasError );

                if ( hasError ) 
                {
                    $( this ).attr( "title", errorMessage );
                } 
                else
                {
                    $( this ).removeAttr( "title" );
                }
            }
        }

    });
});


来源:https://stackoverflow.com/questions/13643417/how-to-validate-pattern-matching-in-textarea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!