How to validate pattern matching in textarea?

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.


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

Tags:

Html

Textarea