Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required field validation jquery showing error message

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?????

like image 272
PoliDev Avatar asked Jan 13 '23 21:01

PoliDev


2 Answers

You should remove this labels after that user input some data

$("#Name").focus();
$("#Name").blur(function(){
    var name=$('#Name').val();
    if(name.length == 0){
        $('#Name').after('<div class="red">Name is Required</div>');
    }
    else {
        $('#Name').next(".red").remove(); // *** this line have been added ***
        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 {
        $('#Address').next(".red").remove(); // *** this line have been added ***
        return true;
    }
});

jsfiddle: DEMO

like image 97
frogatto Avatar answered Jan 17 '23 16:01

frogatto


Your code has bug that it places div as many as time as you blur in empty textbox. This bug is also removed by my code See-:

Working Demo http://jsfiddle.net/XqXNT/

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

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

});

It's better if you use required attribute which does the same work with less code and better manner.

HTML5

<input type="text" name="name" required />
<input type="text" name="address" required />
like image 24
Tushar Gupta - curioustushar Avatar answered Jan 17 '23 18:01

Tushar Gupta - curioustushar