0

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.

ILearner
  • 131
  • 4
  • 16

2 Answers2

2

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

The following regex should do what you want:

^(?=.*(?:(?:\d[ -]?){1,12}))\d(?:[0-9 -]*\d)?$

Explanation:

^ = from start

(?=.* Look ahead for zero or more of any character followed by:

(?: start a non capturing Group of

\d[ -]? a digit followed by an optional Space or hyphen

{1,12} Match 1 to 12 of those digits

\d match a digit

(?: start a new non capturing Group

[0-9 -]*\d a digit or a Space or a hyphen (zero or more) followed by a digit

? makes the Group optional

$ match the end of the string

This will match strings with up to 12 numbers (+ Spaces and hyphens).

Poul Bak
  • 10,450
  • 5
  • 32
  • 57