How to check HTML5 textarea using a regular expression?

Apparently, in HTML5 textarea does not support the pattern attribute.

So how, then, check the characters that the user enters?

    1 answer 1

    The answer is here (SOen).

    You must implement this function yourself:

    $('#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; }); } 
     :valid, .ok { color: green; } :invalid, .error { color: red; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post"> <textarea name="test" pattern="[az]{1,30}(,[az]{1,30})*" id="test"></textarea> <input type="submit" /> </form> 

    PS You need to file the code with a file, but he showed the idea.

    UPDATE :

    For HTML5 validity HTML5 you need to replace the original:

    • HTML : pattern="[az]{1,30}(,[az]{1,30})*" -> data-pattern="[az]{1,30}(,[az]{1,30})*" .
    • JS : $(textarea).attr('pattern') -> $(textarea).data('pattern') .
    • So HTML code will not be valid HTML5 - gilo1212
    • What is the problem - to replace the pattern attribute on the data-pattern and everything will be fine. - user207618
    • Bike on javascript. - user208916
    • @Khipster, can you suggest something better? Welcome. - user207618
    • @Other I get your point. Well, in general exactly what he came up with in one minute ... Eh ... For some reason, there is nothing more practical. Thank. - gilo1212