SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Dec 2002
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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 :
    http://jsbin.com/AcENopog/2/edit


    Thanks, your help is appreciated.

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,411
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    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:

    Code JavaScript:
    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:

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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •