March 12, 2012

Jquery Empty validation for text box

Question by user1263374

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;
  }
});

Answer by Starx

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>');
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!