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

3

Well, 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 goes on, 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 is wrong, change the background color and the field border that the input is wrong, by event change() even without submitting the page. Changing the CSS attributes I know, but how do I get the value that the regular expression does not.

I'm working with JQuery myself.

    
asked by anonymous 27.08.2014 / 21:09

3 answers

5

In properly supported browsers , you resolve this by CSS :

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

link

    
27.08.2014 / 21:19
2

I think it's more or less this:

$(':text').change(function() {
   var pattern = $('[name=nome]').attr('pattern');
   var str     = $(this).val();
   var retorno = str.match(pattern); // retorna a resposta do match...
});

There you go with the other inputs as well.

Having the value of the variable retorno you can change the CSS of the input.

    
27.08.2014 / 21:23
2

Complementing @bfavaretto's response, to ensure that the form does not acknowledge fill-in error at startup, you can use another method. A small CSS in conjunction with a Javascript + jQuery suffices:

.invalido { background: red; color: white; }

Script:

$("input").keyup(function(){
    if(this.validity.valid){
        this.className = "valido";
    } else {
        this.className = "invalido";
    }
});

Edit: As always, I forgot about JSFiddle .

Edit 2: In order for it to acknowledge error if the form is blank, the required attribute must be declared in <input /> .

    
27.08.2014 / 21:43