views:

132

answers:

1

I wrote a decimal validation method to validate the text in a texbox:

$.validator.addMethod("decimalCheck", function(value) {
            var v = new RegExp("^\d*[0-9](\.\d*[0-9])?$", "g");
            return v.test(value);
        }, "Error here");

The first time, I inputed "12,34" string to textbox and error message display. The second time, I inputed "12" string to textbox. That is valid string but error message doesn't hide.

Please help me resolving thanks & best regards

+3  A: 

Try this one (also slightly optimized regex with same functionality)

$.validator.addMethod("decimalCheck", function(value) {
    var v = /^\d+(\.\d+)?$/;
    return v.test(value);
}, "Error here");


Your problem is that you need to escape the backslash it self (double escape) else the regex constructor in reality get this string passed in ("^d*[0-9](.d*[0-9])?$")

var v = new RegExp("^\\d*[0-9](\\.\\d*[0-9])?$", "g");

btw. using the g flag here could lead to unexpected results. Better leave it away as you are using ^ and $ anyway.

jitter
Thank jitter very much
Linh