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