To check the native browser input validation, use the ValidityState object that is on the element object.
It provides a few properties to test certain aspects like typeMismatch
that is a boolean describing if the value of the input is a valid syntax for a type (url,email).
var input = document.getElementById('yourInput');
if(input.validity.typeMismatch){
console.log('Input is not valid type');
}
To check general validity you can just check against valid
var input = document.getElementById('yourInput');
if(!input.validity.valid){
console.log('Input is not valid');
}
If using jQuery simply get access to the actual element object, or use jQuery's prop() method to get to the ValidityState object
var input = jQuery('input');
//input[0].validity.valid
//input.get(0).validity.valid etc
if( input.prop('validity').valid ){
console.log('Valid input');
}
Note also that a couple of pseudo css classes are also provided. :invalid
and :valid
if needing to provide validation styling
:invalid {
border:1px solid red;
}
:valid {
border:1px solid green;
}
Demo
var email = $('#email'),
num = $('#anumber');
email.on('input',()=>{
if(email.prop('validity').typeMismatch){
console.log('Invalid email syntax');
}
});
num.on('input',()=>{
if(num.prop('validity').stepMismatch){
console.log('Invalid number step');
}
});
:valid {
border:1px solid green;
}
:invalid {
border:1px solid rgb(255,0,0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="email" type="email" placeholder="Try Email">
<br>
<input id="anumber" step=10 type="number" placeholder="Try a number">
<br>
<input id="arequired" type="text" placeholder="Try a required" required>