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

Question:

Guys, I have the following form:

<!DOCTYPE html>
<html>
<body>
<form action="enviar.php" method="post" accept-charset="utf-8">
<label>Nome<br> 
    <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/>
</label>
<label>Sobrenome<br> 
    <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/>
</label>

...

</form>
</body>
</html>

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.

Answer:

On properly supported browsers , you solve this by CSS:

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

http://jsfiddle.net/007go6vu/

Scroll to Top