HTML5 form validation

Asked

Viewed 811 times

11

I am making a validation form using HTML5 and its own tags to validate the fields. I am using the PATTERN, that limits the character type. But it doesn’t work... Fields are not being locked. "Code", only numbers and "Name", only letters.

Code:

<!DOCTYPE html>

<form>
Codigo: <input type="text" required="required" name="number" pattern="[0-9]"></input>

Nome: <input type="text" required="required" name="text" pattern="[a-z]"></input> 
</form>

How to solve this?

  • 1

    I believe it will help you: http://wbruno.com.br/html/validando-formularios-apenas-com-html5/

  • 2

    It actually works, the attribute pattern does not prevent the user from entering values that are not in the regular expression, but rather avoids these values being sent by the form. Documentation: https://developer.mozilla.org/en/docs/Web/HTML/Element/Input

  • Additionally, if you want to prevent the user from entering non-accepted values you can do this easily using the plugin jQuery Mask (http://igorescobar.github.io/jQuery-Mask-Plugin/).

  • In fact, as soon as I finished this post I started to realize that... Which are only for regular expressions and there is blocking of the fields, which is what I want. Rodrigo, thanks for the links, will help a lot! Thank you all for confirming what you were thinking.

2 answers

8


Validation does not block fields, just check their invalid status. If you change the invalid field style, this will be visible:

input:invalid {
    background: red;
    color: #fff;
}
<form>
Codigo: <input type="text" required="required" name="number" pattern="[0-9]">
Nome: <input type="text" required="required" name="text" pattern="[a-z]">
</form>

Notice that the rules you set are for 1 number in the first field, and 1 letter (lower case) in the second. If you want to validate multiple numbers and letters you would need to change the regular expressions to [0-9]+ and [a-z]+.

  • 4

    It is worth mentioning that the Pattern attribute works with regular expressions.

  • 1

    I made a short edition to include the term

0

Browser other questions tagged

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