-1

config.newValue has value as "888888888888" and config.regex has value as "/[0-9]{12}/"

let matches = String(config.newValue).trim().match(config.regex);

variable matches should return value as true but it is returning value as null .

Can anyone please help what it is not accepting the correct validation.Validation is only to check that the number is of size 12 and it has digits from 0 to 9 .

N.F.
  • 3,844
  • 3
  • 22
  • 53
sukesh
  • 21
  • 1
  • 5

2 Answers2

0

You have three issues.

  1. If you want to check the value length is exactly 12, Your regular expression should be /^[0-9]{12}$/.

  2. I guess you define config.regex with quotation like const config.regex = "/^[0-9]{12}$/". You have to define regular expression variables without quotation like const config.regex = /^[0-9]{12}$/;

  3. The method match returns the matched string. If you just want true or false, you can use test method. let matches = config.regex.test(String(config.newValue));.

N.F.
  • 3,844
  • 3
  • 22
  • 53
  • i want to get only the matched string . i have config.setRegex('/^\d{12}$/') to insert value in config. regex and for config.newValue ,it is getting whatever value user is entered from UI . I have used let matches = String(config.newValue).trim().match(config.regex) . But still everytime value is matches is coming as null. – sukesh Sep 20 '22 at 07:06
  • regex: string; setRegex(regex) { this.regex = regex; return this; }. This is how i have defined regex and set the value in it. – sukesh Sep 20 '22 at 07:10
  • (1) You have to define `regex` as `RegExp`. `regex: RegExp; setRegex(regex) { this.regex = regex; return this; }`. (2) you have to call `config.setRegex` without quotation like `config.setRegex(/^\d{12}$/)`. – N.F. Sep 20 '22 at 07:20
0

Here is my proposal

const config = {
  newValue: "888888888888",
  regex: "^[0-9]{12}$",
}

const allMatches = String(config.newValue).trim().match(config.regex);
const hasMatch = allMatches && allMatches.length > 0;
const fistMatch = hasMatch ? allMatches[0] : undefined; 

I have created a working example. Click the link and then click [Run] on the right side you'll see console log output results

Working typescript playground

Svetoslav Petkov
  • 1,117
  • 5
  • 13