Problem

By default jQuery validator  uses only validation by “dot” separator.

default code:

jQuery.extend(jQuery.validator.methods, { 
       number: function(value, element) { 
       return this.optional(element) 
        || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value) 
       } 
});

I needed plugin that would allow “comma” separator.

Solutions

Simple or operator :

jQuery.extend(jQuery.validator.methods, { 
         number: function(value, element) { 
            return this.optional(element) 
            || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value) 
            ||  /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); 
          }
});

Combining two regexps. Not optimal but if you don’t know regexp its “good enough”.

brute force version :

jQuery.extend(jQuery.validator.methods, { 
         number: function(value, element) { 
            var val =  value.replace(',','.');
            return this.optional(element) 
             || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(val);
          }
});

Simple but effective version with string replace.

One regexp :

jQuery.extend(jQuery.validator.methods, { 
         number: function(value, element) { 
            return this.optional(element) 
             || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:[,.]\d+)?$/.test(value);
          }
});

Best Solution ;]

Share