0

How to validate these conditions in javacript?

  1. Minimum of 3 digits,
  2. Maximum of 5 digits,
  3. Decimal point after the third digit

Correct values samples:123 , 123.1, 123.55.

1
  • 1
    Should 123. (decimal point without decimals) be accepted or rejected? Commented Apr 9, 2015 at 4:41

2 Answers 2

1

Use RegExp

/^(\d{3})(\.\d{1,2})?$/.test(number+'');


Explanation

\d{3}) means any digits, exactly 3 times

(\.\d{1,2})? is more complicated. It means after the three digits, there can be: A decimal, a digit 1-2 times


Tests

  • 123 -> true
  • 123.4 -> true
  • 123. -> false
  • 123.45 -> true
  • 123.456 -> false
  • 12 -> false
  • 1234 -> false


This accepts both a string and a number

Sign up to request clarification or add additional context in comments.

4 Comments

You don't need to put \d in square brackets.
He said minimum of 3 digits, your RE allows 1 digit.
Why do you need === number+''? .match() returns false if the RE doesn't match.
And shouldn't you have ^ and $ anchors?
0

Regex: /^\d{3}(?:.\d{1,2})?$/

var pattern = /^\d{3}(?:.\d{1,2})?$/;
pattern.test(number);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.