mjnoach
mjnoach

Reputation: 179

How to detect HTML email input validation with JavaScript?

Similarly as to when you can detect wether an input element with a required attribute was correctly validated, writing the following code:

if($('input').attr('required')) {
   alert(1);
}

How can I check if an input of type='email' was a valid entry?

EDIT:

I am not asking about how can I validate the input by comparing it to regex.

When you set the input type attribute to 'email', the submitted string has to have a proper format (it needs to contain '@' symbol and have a proper ending) because otherwise you won't be able to submit the form. What I want to achieve is to prevent the default action of form submit and check what is the state of that email input validation similarly as to when you can check if the required input was provided.

Upvotes: 5

Views: 6302

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

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>

Upvotes: 11

Related Questions