jquery know if field was valid with correct pattern

1

Well, I have a text field:

<input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />

How do I JQuery to see if the fill is in accordance with padrão ?

Yes, I know that html5 already does this for me.

But the validation will be done by botão of fora of form .

Crazy witch. But that's the way it needs to be done.

    
asked by anonymous 01.06.2016 / 13:21

1 answer

2

You do not need jQuery, the validation API itself allows this.

You can use the checkValidity method to check if the input is valid, so you can access the properties of the validity property to find out what validations input has not passed.

var campo = document.getElementById("campo");
var verifica = document.getElementById("verifica");
verifica.addEventListener("click", function (event) {
  if (!campo.checkValidity()) {
    if (!campo.validity.valueMissing) {
      console.log("Campo Obrigatorio");
    } 
    if (!campo.validity.patternMismatch) {
      console.log("Campo com valor invalido.");
    }
  }
});
<form>
  <input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />
</form>
<input id="verifica" type="button" value="Verificar" />

property validity has other useful fields.:

customError
patternMismatch
rangeOverflow
rangeUnderflow
stepMismatch
tooLong
typeMismatch
valueMissing
valid

EDIT - In response to comentatio

The jQuery object is nothing more than an abstraction for your DOM objects, so it ends up working as a container for it, so you can get access to these objects at the index, similar to how you access objects in an Array.

$("#campo")[0] will be similar to document.getElementById("campo"); , but with a huge overhead.

var campo = $("#campo");
var verifica = $("#verifica");
verifica.on("click", function (event) {
  if (!campo[0].checkValidity()) {
    if (!campo[0].validity.valueMissing) {
      console.log("Campo Obrigatorio");
    } 
    if (!campo[0].validity.patternMismatch) {
      console.log("Campo com valor invalido.");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><form><inputpattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />
</form>
<input id="verifica" type="button" value="Verificar" />
    
01.06.2016 / 13:37