regexangularrequiredfieldvalidatorcustomvalidator

Is it possible to modify a pattern Validator to include removing blank spaces written in an input field?


I have a validator running in which I check the format of the phone entered to be compatible with the information requested by the backend. Would it be possible to modify this regex so that it removes or does not take into account if spaces are written between the numbers entered? here my validator

    this.formGroup = this.fb.group({

      mobilePhone: [
        '',
        [
          Validators.required,
          CustomValidators.patternValidator(/^((\+)33|0|0033)[1-9](\d{2}){4}$/, { onlyNumber: true })
        ]
      ],
...


Thank you in advance?


Solution

  • REGEX:

    /^(\+\d{1,3}[- ]?)?\d{10}$/
    

    You can create regex and test on regex101.com Here i have done for mobile number validation

    If Regex Doesn't work then you can create a service for mobile number validation like this :

    SERVICE File (validaion.service.ts)

    import * as PhoneNumber from 'awesome-phonenumber';
    
     static mobileNumberValidator(control) {
        const mobile = new PhoneNumber.default(control.value, 'US');
        return (!mobile.isValid() || !mobile.isMobile()) ? { invalidMobile: false } : null;
      }
    

    TS FILE

    mobileNumber: ['', [Validators.required, 
    Validators.maxLength(13), ValidationService.mobileNumberValidator]],
    
    

    HTML

    <p class="error" *ngIf="editProfileForm.get('mobileNumber').touched && yourformName['mobileNumber'].errors ">
    <span class="error-message" 
    *ngIf="!editProfile['mobileNumber'].errors.required && !editProfile.mobileNumber.errors.invalidMobile">
    Cell phone number is not valid</span>
     </p>