user1263374
user1263374

Reputation:

Jquery Empty validation for text box

I've a text box in a form,when a user submits the form,it should check whether the user has filled it,other validation would be have some min characters,he has to fill.

here is my code,which is not validating


$('.textboxid').bind("submit", function() {
  if($(this).val() == "") {
    jQuery.error('Fill this field');
    return false;
  }
});

Upvotes: 6

Views: 42110

Answers (3)

Avin Varghese
Avin Varghese

Reputation: 4370

 $(function () {

             var textVal = $("#yourTextBoxId").val();
             if (textVal == "") {
                 $("#error").fadeIn(500).show();

             } });

add the div where the error message should appear.

 <div id="error">Enter Value...</div>

Upvotes: 2

Starx
Starx

Reputation: 79069

Your code is not validating because, you are binding submit event on a textbox. You should use forms to do that.

Apart from sudhir's answer, which will work fine. To provide an alternative to it. You can use regex validations too.

An Nice example, which adds errors messages after the textbox as well.

$("#yourFormId").submit(function() {
    var inputVal= $("#yourTextBoxId").val();
    var characterReg = /^([a-zA-Z0-9]{1,})$/;
    if(!characterReg.test(inputVal)) {
        $("#yourTextBoxId").after('<span class="error">Maximum 8 characters.</span>');
    }
});

Upvotes: 3

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

Try:


$("#yourFormId").submit(function() {
  var textVal = $("#yourTextBoxId").val();
  if(textVal == "") {
    alert('Fill this field');
    return false;
  }
});


Upvotes: 7

Related Questions