I want to validate the emails that I have in a text field but I have not found why it gives me an error when the email is supposed to be valid, for this I use a script.
this is what i'm doing
// funcion para validar el correo
function caracteresCorreoValido(email, div){
console.log(email);
var email = $(email).val();
var caract = new RegExp(/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/);
if (caract.test(email) == false){
$(div).hide().removeClass('hide').slideDown('fast');
return false;
}else{
$(div).hide().addClass('hide').slideDown('slow');
// $(div).html('');
return true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel-body">
<form class="form-horizontal m-t-20 toggle-disabled" onsubmit="validacionLogin(); return false;" method="post" >
<div class="form-group">
<div class="col-xs-12">
<!-- <label class="control-label">E-mail</label>-->
<input class="form-control input-lg" type="email" id="email" name="email" data-validation="email" placeholder="Introduce tu correo electronico">
<div id="xmail" class="hide"><h6 class="text-danger">Ingresa un email valido</h6></div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<!-- <label class="control-label">Contraseña</label>-->
<input class="form-control input-lg" type="password" id="password" name="password" data-validation="required" placeholder="Contraseña">
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-lg w-lg waves-effect waves-light" >Iniciar sesión</button>
</div>
</div>
</form>
</div>
<script>
// cuando pierde el foco, este valida si lo que esta en el campo de texto si es un correo o no y muestra una respuesta
$('form').find('input[type=email]').blur(function(){
caracteresCorreoValido($(this).val(), '#xmail')
});
</script>
This line of code is left over:
You're already passing
email
it as a string when you call the function, you don't need to try to read it again (which will cause email to lose its value and your post logic to fail).Making that change, it works fine now:
perhaps the answer does not have much to do with
JavaScript
pure and raw as requested, however for validation issuesinputs
I feel that it should be shared :DBefore continuing I want to make it clear that the implementation by browsers is broad enough to use it with ease, check here: http://caniuse.com/#search=email
Try not to match the result of the test and do it as a function call