Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate the country code with + sign in Angular 7?

I have a text box. There the user can enter the country code with + sign.

If he enters the numbers only, we should not allow him. He must enter the country code with + sign ex: +91, +230, ... I am searching for a regex in the internet. I could not find out a good solution in Angular 7.

Code:

ngOnInit() {

    this.registerFormGroup = this.formBuilder.group({
      clientId: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
      mobileNumber: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
      email: ['', Validators.compose([Validators.required, Validators.email, Validators.maxLength(1000)]) ],
      countryCode: ['', Validators.compose([Validators.required, Validators.pattern('/^[- +()]*[0-9][- +()0-9]*$/')]), ],
    });

    }
like image 965
Kumaresan Perumal Avatar asked Nov 01 '25 09:11

Kumaresan Perumal


2 Answers

Try a regex staring with + and has the desired number of digits

let regex = /^[+]\d{12}$/; // enter the total number if digits you want

let correct = '+911234567890'
let inCorrect = '911234567890'

console.log(regex.test(correct))
console.log(regex.test(inCorrect))

To use \d in angular form validators, it looks like we have to escape the "backslash", so your pattern will be like:

Validators.pattern('^[+]\\d{12}$')

See an example here: https://stackblitz.com/edit/angular-hdctcl?file=src/app/app.component.html

Alternatively you can use:

Validators.pattern('^[+][0-9]{12}$')
like image 112
Ashish Ranjan Avatar answered Nov 02 '25 23:11

Ashish Ranjan


You can try like this

ngOnInit() {

const patternData = /^[+]\d{12}$/;

this.registerFormGroup = this.formBuilder.group({
      clientId: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
      mobileNumber: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
      email: ['', Validators.compose([Validators.required, Validators.email, Validators.maxLength(1000)]) ],
      countryCode: ['', Validators.compose([Validators.required, Validators.pattern(patternData)]), ],
    });
    }
like image 36
Yash Rami Avatar answered Nov 02 '25 22:11

Yash Rami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!