I am trying to validate the form fields by creating my own jquery function so that I can just call it anywhere using only few lines, I have below code but don’t know why its not working:
(function($){
$.fn.validate_form = function(options){
var defaults = {
valid_class: "no_error",
error_class: "form_errors"
};
var new_options = $.extend(defaults, options);
return this.each(function(){
var this_value = $(this).val();
if(!this_value)
{
$(this).removeClass(new_options.valid_class);
$(this).addClass(new_options.error_class);
}
else
{
$(this).removeClass(new_options.error_class);
$(this).addClass(new_options.valid_class);
}
});
};
})(jQuery);
$("#service_title").validate_form();
Here “service_title” is an ID of a text field.
Thanks in advance.
In case there are whitespace characters which you’re missing, I’d pass the field’s value to
$.trim: