E-mail validation via jQuery

Asked

Viewed 484 times

0

I am trying to do a validation in an email field, I even "can" do, but it is not 100% functional, I would like to cancel the button with the disabled attribute, until the user put a valid email, I can cancel the button, but when I type the e-correct mail it does not return.

Input and button

<div>
    <input value="Digite seu e-mail" onclick="this.value=='Digite seu e-mail'?this.value='':''" onblur="this.value==''?this.value='Digite seu e-mail':''" type="text" name="email" id="newsletter" title="Assine nossa newsletter" class="input-text required-entry validate-email input-news validatex"/>
</div>
<button type="submit" class="button btn-inline news-button" id="validatex"><span>Enviar</span></button>

Function

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(email);
}

function validatex() {
  if (validateEmail(email)) {
    $j('#validatex').removeAttr('disabled');
    $j("#newsletter").css("background", "none");
    return true;
  } else {  
    $j("#newsletter").css("background", "url(../../skin/frontend/ultimo/default/images/icon-erro.png) no-repeat 330px #fff"); 
    $j('#validatex').attr('disabled', 'disabled'); 
    return false;
  }

}

$j(".validatex").bind("blur", validatex);
$j("#validatex").bind("click", validatex);

1 answer

1


You need to use keyuo event in input and go checking input content.

The example of the code below working https://codepen.io/anon/pen/oGEoXz?editors=1011

<input type="email" >
<button>Enviar</button>

Your Javascript. Each time the user type is made the validation of the value that is in the input, once that content becomes a valid email we remove the attributes of disabled.

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

$('document').ready(function(){
  $('button').attr('disabled','disabled');
  $('input').keyup(function(){
    if (isEmail($(this).val())){
      console.log('email valido')
      $('button').removeAttr('disabled');
    }else{
       $('button').attr('disabled','disabled');
    }
  })
})
  • It worked, but I would not like to come with the button disabled, I would like to leave it enabled for the client to click and receive the error message to know that it has to be filled but it does exactly what I need..

  • Just remove the line $('button').attr('disabled','disabled'); before the keyup, so the button will not start disabled. Then only do validation in there. Putting field type="email" required Should solve a little bit for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.