Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation plugin: how can I treat errors as warnings and allow form submit?

as the subject suggests, I am using the bassistance.de validation plugin (http://docs.jquery.com/Plugins/Validation/) and I would like to be able to submit the form even when there are validation errors. Basically, we only want to use the plug-in to warn the user of potential issues (please don't question the usability issues with this , I know).

So, is there a way to do it easily or should I hack into the plugin code?

Thanks in advance!

like image 446
AsGoodAsItGets Avatar asked Apr 07 '11 12:04

AsGoodAsItGets


1 Answers

I ran into a similar issue, I decided to use the options.ignore property. http://docs.jquery.com/Plugins/Validation/validate#toptions

$("form").validate({
  rules: {
    "hard": {word_count:10}, // No more than 10 words
    "soft_and_hard": {word_count:[30,10]} // No more than 40 words
  },
  ignore: ".error-okay"
});

I used a custom validator to count words. It was decided that we should display an error after X words (the word count they were asking for), and not allow the form to submit if they have X + T words. When it had between X and X + T words, I would add a class "error-okay" to the element (where ".error-okay" is what I passed as the ignore option).

jQuery.validator.addMethod("word_count", function(value, element, max) {
    var tolerance = 0;
    if (max instanceof Array){
        tolerance = max[1];
        max = max[0];
    }
    var typedWords = jQuery.trim(value).split(' ').length;

    if(typedWords <= max + tolerance) $(element).addClass("error-okay");
    else $(element).removeClass("error-okay");

    return (typedWords <= max);
}, function(max, ele){
    var tolerance = "";
    if (max instanceof Array){
        tolerance = "<br/>Definitly no more than " + ( max[0] + max[1] ) + " words.";
        max = max[0];
    }
    return "Please enter " + max +" words or fewer. You've entered " +
            jQuery.trim($(ele).val()).split(' ').length + " words." + tolerance;
});

If you have multiple validations on a field, you're probably better off writing a invalidHandler function, possibly combining it with added classes like I used (eg: "word-count-okay").

like image 70
whitehat101 Avatar answered Oct 12 '22 13:10

whitehat101