A while ago I've written a custom validation method for .validate(). It is a local validation plugin, with some limited validation.
I was required to write a validation method with the following requirements:
- Must accept a custom string.
- Must allow a maximum value.
- Must allow a minimum value.
- Has to allow to have dynamic values on the string.
- Must validate using a regular expression.
- Must allow numbers in the Portuguese and English formats.
At the time, it was quite a challenge and I was happy with the result, but the code is BAD. It works, but it is so hacky and kludged it hurts my soul.
(function(){
var __c_number_between=new String('');
__c_number_between.valueOf=function(){
return 'The value must be between __MIN__ and __MAX__'
.replace(/__MIN__/g,this.min)
.replace(/__MAX__/g,this.max);
};
__c_number_between.toString=function(){return this.valueOf();};
$.validator.addMethod('c_number_between',
function(d,i,o){
var num=d.replace(/\./g,'').replace(',','.')/1;
__c_number_between.min=o.min;
__c_number_between.max=o.max;
return o.max>=num&&num>=o.min;
},__c_number_between);
})();
Yes, that is the code. It fulfills all my needs, but relies on a really bad behaviour in Javascript, which is that objects are passed as a reference. It also relies on Javascript being executed linearly, instead of having multiple threads, which is REALLY bad!
How can I re-write this in a clean and decent way?
Also, worth noticing is that this is a cross-posting from StackOverflow, on the following question: jQuery .validation plugin: help cleaning aditional method