javascript – How to modify form fields if user input is invalid when compared to regular expression with JQuery


Guys, I have the following form:

<!DOCTYPE html>
<form action="enviar.php" method="post" accept-charset="utf-8">
    <input type="text" pattern="^[a-zA-Zà-úÀ-Ú ]{2,30}$" autocomplete="off" title="Somente letras e acentos são permitidos. Até 30 caracteres." name="nome" maxlength="30" required autofocus/>
    <input type="text" pattern="^[a-zA-Zà-úÀ-Ú ]{2,40}$" autocomplete="off" title="Apenas letras, acentos e espaços são permitidos. Até 50 caracteres." name="sob" maxlength="50" required/>



And so the form continues, other fields and the submit button.

I wanted to know how to get the value that the pattern returned, so when the user input is right nothing happens, but if it's wrong, change the background color and the field border that the input is wrong, through the change() event itself, without submitting the page. Changing the CSS attributes I know, but how to get the value that the regular expression doesn't.

I'm working with JQuery myself.


On properly supported browsers , you solve this by CSS:

input:invalid {
    background: red;
    color: white;

Scroll to Top