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.
Thanks in advance.
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 number1234567890123
has 13 digits, which is too long---
contains only hyphens and spaces