2

Working on site where we currently accept US zip codes. I already have jquery validate working for that. What i want to do now is add a drop down for the user to select country, and then based on the country they selected, it will validate the postal code to make sure it matches.

Can someone give me some pointers on how i can do this? Basically, i just need to change the regex the validator function is using based on the country drop down. The (what i assume is) relevant section of the jquery validator function is this:

(function ($) {
$.fn.validate = function (options) {
    var defaults = {
        invalidClass: 'error',
        rules: {
            req: /.{1,}/g,
            email: /[\w\.=-]+@[\w\.-]+\.[\w]{2,3}/g,
            phone: /\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,
            zip: /\d{5}$|^\d{5}-\d{4}/g,
            //password: /^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$/g,
            password: /^(?=.{8,20}$)(?=.*\d)(?=.*[a-zA-Z]).*/g,
            //nospecialchars: /[^<>?,\/\\\[\]\{\}\|!@#$%^&*()_+;:"]{1,}/g
            nospecialchars: /^(?!.*[?<>;]).+$/g
        },
        error_messages: {
            req: 'Oops..',
            email: 'Please enter your email address.',
            phone: '',
            zip: 'Please give me a valid zip.',
            max: 'too many characters.',
            password: '',
            nospecialchars: ''
        },
        success: null,
        failure: null
    },
    errors = [],
    opts = $.extend(true, defaults, options);

    return this.each(function () {
        var $this = $(this);

        $(this).find('input[type="submit"]:not(.cancel), button').click(function () {
            errors = [];
            validate_fields($this);

            if ($this.find('.error').length === 0) {
                if (typeof opts.success == 'function')
                    return opts.success();
            }
            else {
                if (typeof opts.failure == 'function')
                    return opts.failure(errors);
            }
        });
    });

I'm not very familiar with jquery so i don't know what the syntax is here for me to create an if-else or case statement to set the regex.

Thanks if advance for any help.

edit: Here's the bit of code that actually calls the validation

   <script type="text/javascript">
    $(function () {
        setForm();

        $('form').validate({
            error_messages: {
                req: null
            },
            failure: function (errors) {
                var sel = '';

                $(".errMsg").hide();
                for (x in errors) {
                    sel += ',#' + errors[x][0];
                }

                if (sel.length > 0) {
                    sel = sel.substring(1);

                    $(sel).parent().find(".errMsg").show(0, function () {
                        $('#home .orange_box, #home .HomeRight').height('auto');
                        $('#infov .white_box, #infov .orangeRight').height('auto');
                        $('#findt .orange_box, #findt .HomeRight').height('auto');

                        if ($.browser.msie && $.browser.version == 8) {
                            evenColumns('#home .orange_box', '#home .HomeRight', -16);
                            evenColumns('#infov .white_box', '#infov .orangeRight', -16);
                            evenColumns('#findt .orange_box', '#findt .HomeRight', -16);
                        }
                        else {
                            evenColumns('#home .orange_box', '#home .HomeRight', -15);
                            evenColumns('#infov .white_box', '#infoforv .orangeRight', -15);
                            evenColumns('#findt .orange_box', '#findt .HomeRight', -15);
                        }
                    });
                }

                return false;
            },
            success: function () {
                $(".errMsg").hide();
                return true;
            }
        });
merk
  • 1,721
  • 5
  • 23
  • 39
  • 1
    Normally, based on a user's locale, I'd use localization to load different assets. For example: User visits site. Sets language choice to french, country to Canada. Their culture is now fr_CA. I use fr to load french content, and CA for purposes such as determining which form of address validation to use. This is, by all means, the easiest way I've encountered for dealing with things like this. – Steve Adams Nov 17 '11 at 00:35
  • i agree - but it's not an option right now since the client doesn't want to implement locales. They just want this one spot on the site where the user can select a country and input a postal code. Although - maybe i should just do a 'cheap' version of this - i could have the country dropdown determine what JS file gets loaded. But i'd still like to know how to do it within jquery anyhow just so i know in the future how to do it. – merk Nov 17 '11 at 04:25

1 Answers1

0

I would create an object, witch has:

  • function for the validation
  • object for all other countries
  • object for default rules
   validation = {
      validate : function( sCountryName, sToValidate ){
        return ( null != sToValidate.match( this.countries[ sCountryName ] ? this.countries[ sCountryName ].zip : this.defaultRules.zip ))
      },

      countries : {
        england : {
          zip : /\d{5}$|^\d{5}-\d{4}/g
        }
      },
      defaultRules : {
        zip : /\d{5}$|^\d{5}-\d{4}/g
      }
    }
p1100i
  • 3,710
  • 2
  • 29
  • 45
  • Thanks for the suggestion. Would i place your bit of code inside the rules: section that i posted in my original post? Mainly the 3rd line, return (......) ? – merk Nov 17 '11 at 04:34
  • Well it depends how do u wanna call the function, because u didnt include that part of your code, just the regexps. You could rename in your code the "rules" object to "defaultRules" then add "countries" object from my code, and add "validate" function from my code. With $.fn.validate.validation( "england", "213123" ) you should get your results. – p1100i Nov 17 '11 at 09:39
  • Sorry about that - I've edited the original post to include how the validation is being called. Thanks – merk Nov 17 '11 at 16:30
  • Well if you want me to modify that function for you, you'll need to include the rest of that function too ( $.fn.validate ). – p1100i Nov 17 '11 at 16:57
  • Sorry - i wasn't trying to be difficult. I was just trying to avoid cluttering up the page with extra code. I've edited my original post to include the full functions. – merk Nov 18 '11 at 02:14
  • Still that validate_fields($this); methods definition is missing. – p1100i Nov 18 '11 at 12:07
  • Actually, as far as i can tell, i've included all the code dealing with the validation. Don't i just need to edit the function itself without editing the call to the function? i.e. can't i just do something where i check what the value is of the country drop down and then based on that set the regex pattern. Does the value of the country drop down need to be explicitly passed? I thought i could access it within the function itself since i can obviously access the value of the zip code box to compare to the regex pattern, no? Thanks – merk Nov 21 '11 at 23:17
  • ye, thats right, but the validate_field method somehow call your $.fn.validate function, and that is needed if u want me to edit your implemention. Btw my answer holds already the logic for your solution, but as i see, you don't get it, that's why i wanted to wrote it directly for u. – p1100i Nov 22 '11 at 16:07
  • yeah sorry - I haven't really done anything with jquery before so i'm not too familiar with it. I thought this chunk of code was calling the validation: $(function () { setForm(); $('form').validate({ – merk Nov 23 '11 at 18:33