How validate both or either one?

I have two text fields in a search form, the user can search by ip1 or by ip2 or by both, I want only the ip address filled to be validated and skip the other one if left empty, I did this but it’s still not working :[COLOR=#333333]

Thanks, your help is appreciated.
[/COLOR]

Hi mlotfi,

The problem is that your function for validating the IP address returns false for an empty field, meaning the form will never be valid with just one IP. Fortunately, the validation library gives you a way to check if the field is optional or not. Here’s how you could do that:

var ipPattern = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/,
    invalidValues = ["0.0.0.0", "255.255.255.255", "10.1.0.0", "10.1.0.255"];

function isValidIP(value) {
	var ipArray = value.split('.');

	if (!value.match(ipPattern)) {
		return false;
	}

	for (var i = 1; i <= 4; i++) {
	  if (ipArray[i] > 254) {
	    return false;
	  }
	}

	if ($.inArray(value, invalidValues) >= 0) {
		return false;
	}

	return true;
};

jQuery.validator.addMethod("ipAddressFormat", function(value, element) {
	return this.optional(element) || isValidIP(value);
}, "Invalid IP Address");

I’ve moved the validation logic out into a separate function to make checking for the optional field easier. I’ve also made a couple changes to the validation method, moving a couple of variables outside of the function (to prevent them being reassigned every time the function is run) and removing some redundant checks.

The other thing you need to do is change the require_from_group options to only require 1 of the 2 IP fields to validate:

valueApiAddress: {
	ipAddressFormat: true,
	require_from_group: [1, ".ipAddy"]
},
valueExternalApiAddress: {
	ipAddressFormat: true,
	require_from_group: [1, ".ipAddy"]
},