I am trying to validate a login form. I am taking children of a div and iterating to all input elements. Everything working fine.But when focus moves on to password field and if i remove all values of username it doesn't give required error. My code
<div class="login-contents">
<input type="text" name="name" class="form-control login-check" id="login-name" placeholder="Username">
<input type="password" name="pass" class="form-control login-check" id="login-pass" placeholder="Password">
</div>
<div id="login-error" class="alert alert-danger"></div>
And Jquery
$(document).ready(function(){
$("#login-form").prop("disabled",true);
$("#login-error").removeClass("alert alert-danger");
var name_min_length = 2;
var pass_min_length = 5 ;
$(".login-contents").children('input').each(function(){
$(".login-check").keyup(function(){
var name = $("#login-name").val();
name = jQuery.trim(name).length;
var name_length = length_check(name,name_min_length);
console.log(name_length);
var pass = $("#login-pass").val();
pass = jQuery.trim(pass).length;
var pass_length = length_check(pass,pass_min_length);
console.log(pass_length);
});
});
function length_check(value,number){
if (value < number) {
$("#login-error").addClass("alert alert-danger").html("Minimum length");
}
else{
$("#login-error").removeClass("alert alert-danger").html("");
return true ;
}
}
});
Any suggestion where i am doing wrong
Everything seems right you just need to change your logic like following with lesser code:
No need of .each loop in this case you can access this (current element where keyup fired) in your code by using class selector .login-check!
$(".login-check").keyup(function(){
var name = $(this).val();
var elemType = $(this).attr('name')
name = jQuery.trim(name).length;
var length = length_check(name, elemType == 'name' ? name_min_length : pass_min_length); // if element is name length will be 2 otherwise 5 for pass
console.log(length);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With