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()
– Carlos Rocha
Consegui:if (!$("#cep")[0]. checkValidity(). Obrigado!
– Carlos Rocha
@Carlosrocha, I made an edition in the reply.
– Tobias Mesquita