Html 如何验证textarea中的模式匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13643417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:09:35  来源:igfitidea点击:

How to validate pattern matching in textarea?

htmltextarea

提问by Riesling

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?

当我在 javascript 中使用 textarea.checkValidity() 或 textarea.validity.valid 并且具有无效值时,这两个总是返回true,我做错了什么?

<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/

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

回答by Dipesh Shah

HTML5 <textarea>element does not support the patternattribute.

HTML5<textarea>元素不支持该pattern属性。

See the MDN docfor allowed <textarea>attributes.

有关允许的属性,请参阅MDN 文档<textarea>

You may need to define this functionality yourself.

您可能需要自己定义此功能。

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

或者遵循定义 JavaScript/jQuery 函数的传统 HTML 4 实践来执行此操作。

回答by Yann Dìnendal

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.patternMismatchcan set manually, but you could use your own property instead, if needed.

您可以使用setCustomValidity(). 这样,this.checkValidity()将回复您要应用于元素的任何规则。我认为this.validity.patternMismatch不能手动设置,但如果需要,您可以改用自己的属性。

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

http://jsfiddle.net/yandinendal/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;
    });
}

回答by dwkd

This will enable the patternattribute 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 gRegex flag:

这将启用patternDOM 中所有文本区域的属性并触发 Html5 验证。它还考虑了具有^or$运算符并使用gRegex 标志进行全局匹配的模式:

$( 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" );
                }
            }
        }

    });
});