2

I trying to accept positive and negative no in angular reactive form validation

 [Validators.required, Validators.pattern("^-?[0-9]d*(.d+)?$")]

It only accept one no after it gives me an error

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
sabban
  • 131
  • 5

2 Answers2

3

You may use

[Validators.required, Validators.pattern("-?\\d+(?:\\.\\d+)?")]

Or,

[Validators.required, Validators.pattern(/^-?\d+(?:\.\d+)?$/)]

NOTES:

  • If you define the regex with a string literal, "...", remember that ^ and $ are appended by angular automatically, you do not need to specify them explicitly AND you need to double escape backslashes to define regex escape sequences, like \d, \w, \b, \W, etc.
  • If you define the regex using a regex literal notation, /.../, you need to add ^ and $ to ensure a full string match, and you need to use single backslashes to define regex escapes.

The ^-?\d+(?:\.\d+)?$ regex is rather basic, you may find more at Regular expression for floating point numbers and Javascript: Regular expression to allow negative and positive floating point numbers?.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

check this works for Integers or decimal numbers with or without the exponential form

^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$

for more regex try this website

Vijay Bhati
  • 71
  • 1
  • 2