Search code examples
javascriptregexangular-reactive-formsphone-number

JavaScript RegExp For Phone number validation that need to allowing hyphens and space in between the numbers


App.component.html

<form [formGroup]="exampleForm">
       <div class="form-group">
         <label>First Name</label>
       <input type="text" formControlName="phoneNumber" class="form-control" >
      </div>
  </form>

App.component.ts

exampleForm: FormGroup;
   number_pattern=' ^[0-9_-]*$ ';

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.exampleForm = this.formBuilder.group({
            phoneNumber: ['', Validators.required, Validators.pattern(number_pattern)]
        });
    }

I need regex for phone with following rules, I tried regex code but its not working.

  1. Field must not be empty.
  2. Hyphens and space will accept in between the number not the starting and ending.
  3. Must not contain anything other than numbers or blank spaces or hyphens
  4. Field must not contain only blank space
  5. Field must not contain only hyphens
  6. Field must not contain only hyphens and blank space.

Thanks in advance.


Solution

  • Try the following pattern:

    ^\d([0-9 -]{0,10}\d)?$
    

    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('123'));             // pass
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('1-2 3'));           // pass
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('1-2-3-4-5-6'));     // pass
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('1-2-3-4-5-6-'));    // fail
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('123456789012'));    // pass
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('1234567890123'));   // fail
    console.log(/^\d([0-9 -]{0,10}\d)?$/.test('- --'));            // fail

    The three examples which fail above do so because:

    • 1-2-3-4-5-6- ends in a hyphen, not a number
    • 1234567890123 has 13 digits, which is too long
    • --- contains only hyphens and spaces