JSFiddle - React, Tailwind, and code Playground

by Pasky Org

HTML

<form method="post">
    <textarea name="test" pattern="[a-z]{1,30}(,[a-z]{1,30})*" id="test"></textarea>
    <input type="submit" />
</form>

CSS

:valid, .ok {
    color: green;
}
:invalid, .error {
    color: red;
}

JavaScript

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


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

function validateTextarea() {
				debugger;
        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;
        });
    }