1

I am trying to use RegExp validation for a number that can have up to 5 numbers followed up one option decimal place. Like 48293 or 23.4 are good. 99.99 or 453543 are not. I wrote the following function:

function validateLoad(load_value) {
 var matchValue = new RegExp('[0-9]{1,5}(\.[0-9]{1})?')
 return matchValue.test(load_value)
}

However, this seems to return true for all numerical values, can anyone tell me how to fix this?

1
  • 1
    up to means from 0, then you should change to [0-9]{0,5} Commented Nov 20, 2013 at 20:55

2 Answers 2

3

You need to use anchors to make sure the entire string (and not just a substring) is matched by the regex. Also, don't forget to double the backslashes if you construct the regex from a string (and drop the {1}, it's a no-op):

var matchValue = new RegExp('^[0-9]{1,5}(\\.[0-9])?$');
Sign up to request clarification or add additional context in comments.

1 Comment

@thomas: No operation - a command without any effect. Every token is matched exactly once by definition, unless stated otherwise. So x and x{1} are identical.
0

Using literal notation would avoid to escape backslashes :

function validateLoad(load_value) {
    return /^\d{1,5}(\.\d)?$/.test(load_value)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.