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

Asked

Viewed 1,211 times

3

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 Pattern returned, so when the user input is right nothing happens, but if it is wrong, change the background color and the edge of the field that the input is wrong, by the event change() same, without submitting the page. Change the CSS attributes I know, but how to get the regular expression value not.

I’m working with Jquery anyway.

3 answers

5


  • 1

    And if anything else has to be done via code, just check to access the property validity.valid of inputs: true means valid; false, invalid.

  • Cool @Ruipimentel, I didn’t know this.

  • I had no idea. The only problem is that the fields, they start after loading, theoretically invalid, in matter of appearance does not get very cool

  • @leandro17br But I think this could be solved in the regex, no?

2

I guess that’s about it:

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

Then just do with the other inputs too.

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

2

By complementing the @bfavaretto response, to ensure that the form does not file an error on startup, you can use another method. A small CSS together with a Javascript+jQuery is enough:

.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 the Jsfiddle.

Edit 2: in order for it to error if the form is empty, it is necessary that the attribute required be stated in the <input />.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.