jQuery ValidationEngine: How to validate that at least one of a set of fields is not empty?
Asked Answered
N

6

15

In our project we are using ValidationEngine, and we don't have the ability to replace it with another plug-in.

Our form has ten inputs and some of them are optional, but at least one of the optional fields must be included.

So, how do you validate inputs in this case?

Sample:

form
  input1
  input2
  intpu3

input1: required

At least one of input2 and input3 must be present -- if both are empty validation should fail.

Naze answered 11/2, 2011 at 15:45 Comment(1)
+1 Did you find an answer to this question yet?Mclaurin
H
17

The validation engine now supports group Validation.Go to jQuery form validation plugin @ github and ake a look at groupRequired. The syntax looks something like this.

<input value="" class="validate[groupRequired[payments]]" type="text" name="creditcard" id="creditcard" />
<input class="validate[groupRequired[payments]]" type="text" id="paypal" name="paypal"/>
Homo answered 8/6, 2011 at 15:52 Comment(1)
Note to others - I was a bit confused as to what 'payments' was in the above example or what it referenced - as all of the others validators reference another fields id - but 'payments' is just any arbitrary term that you keep common across the fields you want to group. Also 'groupRequired' wont work on check boxes I found out. I assume because they already have a value s it will default to valid - irrelevant of if it is checkedRodina
B
4

It appears that the ValidationEngine plugin allows you to specify a validation rule which uses a custom function to determine validity.

If you add the validate class on input1 like so...

<input id="input1" class="validate[required,funcCall[myValidationFunction]]" />

Then ValidationEngine will use the following function. You can pretty much put any kind of logic in there. If I read your scenario correctly, this should accomplish what you're after.

function myValidationFunction() {
  var input1 = $.trim($("#input1").val());
  var input2 = $.trim($("#input2").val());
  var input3 = $.trim($("#input3").val());

  if (input1.length == 0) {
    return "input1 is required";
  }

  if (input2.length == 0 && input3.length == 0) {
    return "Either input2 or input3 is required";
  }

  // We don't need to return anything if there is no error.
}

Here's a link to the _funcCall function in the source code: https://github.com/posabsolute/jQuery-Validation-Engine/blob/master/js/jquery.validationEngine.js#L574

Benedic answered 9/5, 2011 at 18:54 Comment(2)
+1 nice example, except that I think he wants field 1 to be required in all cases, and at least one of fields 2 and 3 to be present. So the if statement could use a minor rewrite.Handedness
I was getting "options.customFunctions is undefined" in the console until I defined the function as myValidationFunction = function() {...}Foulk
C
4

In case someone wants to make groupRequired work for checkboxes, you need to add error messages to your language file for groupRequired. e.g. if it is jquery.validationEngine-en.js, it should be like this:

"groupRequired": {
  "regex": "none",
  "alertText": "* You must fill one of the following fields",
  "alertTextCheckboxMultiple": "* Please select an option",
  "alertTextCheckboxe": "* This checkbox is required"
}
Cos answered 2/2, 2014 at 11:26 Comment(2)
It's a bit dirty to do it that way (if you are not careful it gets overwritten at the next update). However I wonder why this is not added by default...Lemaceon
Thank you! Why this wasn't used originallySnort
A
0

One solution could be to attach validations before validating and removing after validation is over.

jQuery(document).ready(function(){
    jQuery("#formID").validationEngine();

    $("#formID").bind("jqv.form.validating", function(event){
        var fieldsWithValue = $('input[type=text]').filter(function(){
            if($(this).val().length>0){
                return true;
            }
        });
        if(fieldsWithValue.length<1){
            $('input[type=text]').addClass('validate[required,funcCall[requiredOneOfGroup]]');
        }
    });

    $("#formID").bind("jqv.form.result", function(event, errorFound){
        $('input[type=text]').removeClass('validate[required,funcCall[requiredOneOfGroup]]');
    });
});

function requiredOneOfGroup(field, rules, i, options){
    var fieldsWithValue = $('input[type=text]').filter(function(){
        if($(this).val().length>0){
            return true;
        }
    });
    if(fieldsWithValue.length<1){
        return "At least one field in this set must have a value.";
    }
}
Ataman answered 5/5, 2011 at 20:34 Comment(0)
M
0
!!$('#input2,#input3').filter('[value]').length
Marsupium answered 10/5, 2011 at 6:54 Comment(3)
This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.Pepi
@Pepi - No, it's really not. That line of code validates what the OP asked for. Please don't make incorrect critical comments of posts that are over a year old that you haven't even bothered to understand.Marsupium
Sorry -- you're right, it's clearly a valid answer. FYI that comment text is SO-generated. This asnwer was automatically flagged by SO as "low-quality because of its length and content" and placed in the "Low Quality Posts" queue for review. There are almost 40k posts in there right now, so I've been trying to help with the reviews, chopping at dozens a day lately. I must have hit the wrong button. I generally accept all the 1-liner jQuery answers as I'm well-versed in the framework, so this was a mistake.Pepi
S
-1

There is a provision in jquery validation plugin to make grope of of elements.

groups: {groupName: "text1 text2 text3 .. so on"}

errorPlacement: function(error, element) {
                    // Write Done your business logic to display error 

             if ( element.attr("name") == "text1" -- define other text elements also) {
               error.insertAfter("#error_location_placeholder_id");
                    }else{
               error.insertAfter(element);
             }               

           }

and you business validation in rules method for at least one must be not empty logic

groupName:{

                    required: function(element) {
// Your business logic for validation

                        if( $("#text1").val().length > 0 ){
                            return false;
                        }else{
                            return true;
                        }

                    }
                }
Someplace answered 9/5, 2011 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.