0

I am trying to ensure that the user can only enter a decimal. I found a reg expression that checks for this, but it's seemingly working in the reverse of how I'd like it to. Right now if the user enters a non decimal the button on my form gets enabled. I want the button to get enabled only if the user enters a decimal. Here is my code.

            decimal: function (val/*,rule*/){
                if(!val){
                    return true;
                }
                return /^[0-9]{1,6}(?:[,.][0-9]{0,5})?$/.test(val);
            },
Chaim Friedman
  • 6,124
  • 4
  • 33
  • 61
  • STOP! No regex! Capture the keyboard event before you are going to filter replace do stuff. check the demo in my [previous answer](http://stackoverflow.com/questions/29543514/how-to-realtime-calculate-values-from-input-checkbox-radio-and-selectbox/29546405#29546405) – Tim Vermaelen May 19 '16 at 15:44
  • If your expression matches the regex it returns true. From what i can see, if you have no value you return true aswell. So you can do "return !regex.test(val);" – Groben May 19 '16 at 16:01

2 Answers2

1

Your function works fine. I suggest reversing the returning value like this:

decimal: function (val/*,rule*/){
    if(!val){
        return true;
    }
    return !/^[0-9]{1,6}(?:[,.][0-9]{0,5})?$/.test(val);
}
Martin Gottweis
  • 2,721
  • 13
  • 27
1

This regex works to ensure the user has entered a decimal value (upto 2 points (eg.785747.12))..

\d+(\.\d{1,2})?

I got this from Simple regular expression for a decimal with a precision of 2

I hope this helps.

Community
  • 1
  • 1