How to validate pattern matching in textarea?

后端 未结 3 575
情话喂你
情话喂你 2020-12-01 12:17

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?

&         


        
3条回答
  •  攒了一身酷
    2020-12-01 12:44

    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;
        });
    }
    

提交回复
热议问题