jquery to know if field was validity with correct default

Asked

Viewed 94 times

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 do in JQuery to know if the completion is in accordance with the padrão?

Yeah, I know the html5 already does it for me.

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

crazy thing. But this is how it needs to be done.

1 answer

2

No need for jQuery, the own validation API allows you to do this.

You can use the method checkValidity to check if the input is valid, then you can access the property properties validity to know in which validations the input did not pass.

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" />

the property validity has other useful fields.:

customError
patternMismatch
rangeOverflow
rangeUnderflow
stepMismatch
tooLong
typeMismatch
valueMissing
valid

EDIT - In Response to Comments

The jQuery object is nothing more than an abstraction for your DOM objects, so it turns out to function as a container for the same, this way you will be able to access these objects through the Dice, 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>
  <input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />
</form>
<input id="verifica" type="button" value="Verificar" />

  • Yes. But I already use Jquery. In case it would look like this? if (!$("#field"). checkValidity()

  • Consegui:if (!$("#cep")[0]. checkValidity(). Obrigado!

  • @Carlosrocha, I made an edition in the reply.

Browser other questions tagged

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