Search code examples
javascriptangularangular7

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]*$/')]), ],
    });

    }

Solution

  • 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}$')