-1

My login page have three things:

  1. Field for the username
  2. Field for the password
  3. Submit button

This code will disable the submit button if the username field is not empty.

I want to disable the submit button until the username field is filled with a email.

Additionally, After wrote something in the username field and clear it, the submit button does not disable itself. I want the submit button to disable itself after clearing the username field.

$(':input[type="submit"]').prop('disabled', true);
 $('input[type="email"]').keyup(function() {
    if($(this).val() != '<!-- not sure what to put here -->') {
       $(':input[type="submit"]').prop('disabled', false);
    }
 });
DanCode
  • 525
  • 3
  • 7
  • 25

2 Answers2

2

You can use RegEx to validate email. You have to disable the button if the condition is false like the following way:

let button = $(':input[type="submit"]');
button.prop('disabled', true);
$('input[type="email"]').keyup(function() {
  if(validateEmail($(this).val())) {
     button.prop('disabled', false);
  }
  else{
    button.prop('disabled', true);
  }
});
 
function validateEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="email"/>
<input type="submit" value="Submit"/>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thank you! It worked!! I got another question, what does /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ mean ? and how did you come up with it? – DanCode Jun 10 '18 at 04:56
  • @DanCode, that is a pattern which test the input value for valid email pattern. Check out https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript – Mamun Jun 10 '18 at 05:10
2

A pure js solution for this would be:

document.querySelector("input[type=email]").onkeyup = function(){
let reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
(this.value.length==0 || reg.test(this.value)==false)?document.querySelector("input[type=submit]").setAttribute("disabled","disabled"):document.querySelector("input[type=submit]").removeAttribute("disabled")
}
<form>
<input type="email">
<input type="password">
<input type="submit" disabled>
</form>

This checks the length of the input value or the input pattern whenever a key is released. If the length is zero or the pattern does not match, then it sets the disabled attribute to disabled. If not, it removes the attribute disabled altogether.

Yuki.kuroshita
  • 759
  • 9
  • 29