jQuery Validation - Two fields, only required to fill in one

JqueryJquery Validate

Jquery Problem Overview


I'm using the jQuery Validation Plugin on my form. On my form I have a 'Telephone' field and a 'Mobile No.' field.

How would I go about making it so the user has to fill in one of them, but it can be either field?

Jquery Solutions


Solution 1 - Jquery

This looks like what you need to use [dependency-callback][1]

What this will allow you to do is:

> Makes the element required, depending on the result of the given callback.

You can then place a required validation rule on the two telephone fields that will only be required based on the return from the function callback; thus you can put a rule on the telephone field to say require this rule only if the mobile field is blank, and vice versa for the mobile field.

This is untested but in theory

rules: {
    telephone: {
        required: function(element) {
            return $("#mobile").is(':empty');
        }
    },
    mobile: {
        required: function(element) {
            return $("#telephone").is(':empty');
        }
    }
}

Be sure to check comments/other answers for possible updated answers.

[1]: https://jqueryvalidation.org/required-method/ "dependency-callback"

UPDATE

rules: {
     telephone: {
          required: '#mobile:blank'
     },
     mobile: {
          required: '#telephone:blank'
     }
}

Solution 2 - Jquery

I think that the correct way of do this is using the "require_from_group" method.

You can checkit on http://jqueryvalidation.org/require_from_group-method/

The example is exactly what your are searching for:

<input class="left phone-group" id="mobile_phone" name="mobile_phone">
<input class="left phone-group" id="home_phone" name="home_phone">
<input class="left phone-group" id="work_phone" name="work_phone">

<script>
$( "#form" ).validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, ".phone-group"]
    },
    home_phone: {
      require_from_group: [1, ".phone-group"]
    },
    work_phone: {
      require_from_group: [1, ".phone-group"]
    }
  }
});
</script>

It's mandatory to include additional-methods.js

Solution 3 - Jquery

Came here looking for the same answers. Found the above post very helpful. Thanks.

I have extended this solution to check if the other field is in fact valid, rather than just "not empty". This ensures that the user inputs a valid Phone Number before removing the "required" class from the Mobile field and vice versa.

Mobile: {
	required: function(element) {
	return (!$("#Phone").hasClass('valid'));
	}
},
Phone: {
    required: function(element) {
        return (!$("#Mobile").hasClass('valid'));
	}
}

Solution 4 - Jquery

I had troubles is .is(':empty') so here is my working options example.

Before:

rules: {
   name:       {required: true},
   email:      {required: true},
   phone:      {required: true}
}

All fields were required. But I wanted email and/or phone so to create the 'or':

rules: {
   name:       {required: true},
   email:      {required: 
                    function() {
                        //returns true if phone is empty   
                        return !$("#phone").val();
                    }
               },
   phone:      {required:
                    function() {
                        //returns true if email is empty
                        return !$("#email").val();
                     }
               }
},
messages: {
   email: "Email is required if no phone number is given.",
   phone: "A phone number is required if no phone email is given."
}

And you will see that I've added the messages option to give the user some meaningful info because the default messages would say that each field is required which is not true in this situation.

Solution 5 - Jquery

Requirement is Validation need to be either C or (A and B) is required. The thing worked for me is:

$.validator.addMethod("multipeFieldValidator", function(value) { 
	var returnVal = false; 
	if($("#Cfield").val() != '' || ($("#Afield").val() != '' && $("#Bfield").val() != '')) {
		returnVal = true;
	}
	return returnVal; 
}, 'Either C or A and B is required');


$('#Afield.form-control').change(function(){
    $(this).valid();
    $("#Bfield").valid();
    $("#Cfield").valid();
    
});

$('#Bfield.form-control').change(function(){
    $(this).valid();
    $("#Afield").valid();
    $("#Cfield").valid();
});

$('#Cfield.form-control').change(function(){
    $(this).valid();
    $("#Bfield").valid();
    $("#Afield").valid();
});


within rules I have 
Afield: "multipeFieldValidator",
Bfield: "multipeFieldValidator",
Cfield: "multipeFieldValidator" 

Solution 6 - Jquery

$(document).ready(function () {
    jQuery.validator.addMethod("mobile10d", function (value, element) {
        return this.optional(element) || /^[7-9]{1}[0-9]{9}$/.test(value);
    }, "Please enter a valid 10 digit phone number.");
    $("#form_id").validate({
        rules: {
            mobile: {
                required: "#telephone:blank",
                mobile10d: true
            },
            telephone: {
                required: "#mobile:blank",
                mobile10d: true
            }
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form class="" action="" method="POST" id="form_id">
    <div class="col-md-4 form-group">
        <label class="form-control">Mobile<span class="required">*</span></label>
        <input class="form-control" type="text" name="mobile" id="mobile" placeholder="0-9">
    </div>
    <div class="col-md-4 form-group">
        <label class="form-control">Telephone<span class="required">*</span></label>
        <input class="form-control" type="text" name="telephone" id="telephone" placeholder="0-9">
    </div>
    <div class="form-group">
        <input type="submit" name="" value="Submit" class="apply-now-btn">
    </div>
</form>

Solution 7 - Jquery

This Will do

Mobile: {
    required: function(element) {
    return (jQuery.isEmptyObject($("#Phone").val()));
    }
},
Phone: {
    required: function(element) {
        return (jQuery.isEmptyObject($("#Mobile").val()));
    }
}

Solution 8 - Jquery

Thought this might be a helpful addition - no plugin needed. This will handle all input fields inside a div when only one is required. You can alter it to your needs - like creating extra validation on the found inputs.

THE HTML

<div class="MOTHER-DIV">
	-- any content can go here
	-- all inputs will be checked
	-- returns true on one value found
</div>

THE CODE

var hasInput=false;
$(".MOTHER-DIV :input").each(function () {
	if($(this).val()  !== "") {
		hasInput=true;
	}
});
if(!hasInput) {
	alert("nothing found");
} else {
	alert("content found");
}

For checkboxes, use:

var hasCheckBoxInput=false;
$('.OTHER-DIV input[type=checkbox]').each(function () {
	if($(this).is(':checked')) {
		hasCheckBoxInput=true;
	}
});
if(!hasCheckBoxInput) {
	alert("NO checkbox is checked");
} else {
	alert("YES! One checkbox checked");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProbocopView Question on Stackoverflow
Solution 1 - JqueryJeff WilbertView Answer on Stackoverflow
Solution 2 - JqueryeveevansView Answer on Stackoverflow
Solution 3 - JqueryBarbsView Answer on Stackoverflow
Solution 4 - JqueryWarrenView Answer on Stackoverflow
Solution 5 - JquerydevcodeccView Answer on Stackoverflow
Solution 6 - JqueryVijayan JayaramanView Answer on Stackoverflow
Solution 7 - JquerySalim AliView Answer on Stackoverflow
Solution 8 - JqueryKJSView Answer on Stackoverflow