sanket munj 2
sanket munj 2

Reputation: 3

how to validate digit in javascript

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.

Upvotes: 0

Views: 68

Answers (2)

Downgoat
Downgoat

Reputation: 14361

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

Upvotes: 1

Vigneswaran Marimuthu
Vigneswaran Marimuthu

Reputation: 2532

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

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

Upvotes: 0

Related Questions