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