Home > database >  angular regex is not working for 12 digit validation check
angular regex is not working for 12 digit validation check

Time:09-20

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 .

CodePudding user response:

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));.

CodePudding user response:

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

  • Related