Required field validation jquery showing error message

PoliDev picture PoliDev · Jul 20, 2013 · Viewed 45.2k times · Source

I validated some fields in my form.. But i have some issues..If without enter fields it shows error message.. If fill out the field still error message is showing..

How to put that ?

My code

 $("#Name").focus();
$("#Name").blur(function(){
    var name=$('#Name').val();
    if(name.length == 0){
        $('#Name').after('<div class="red">Name is Required</div>');
    }
    else {
    return true;
    }
});

   $("#Address").blur(function(){
    var address=$('#Address').val();
    if(address.length == 0){
        $('#Address').after('<div class="red">Address is Required</div>');
        return false;
    }
    else {
    return true;
    }
});

can anyone help me please?????

Answer

Lucas Willems picture Lucas Willems · Jul 20, 2013

Try this code (I just changed the structure and added return false) :

$("#Name").focus()

$("#Name, #Address").blur(function(){
    if($(this).val().length == 0){
        $(this).after('<div class="red">This field is required</div>');
    } else {
        $(this).next('.red').remove()
    }
});

But I think the best way is to add the required attribute to your fields like this :

<input type="text" name="name" required />
<input type="text" name="address" required />