admin管理员组

文章数量:1398147

In my .ts ponent file, I've a variable like (to restrict an invalid phone number being entered),

public phonePattern = ^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$;

And in my ponent html file, I've a text box declared as,

<input type="text" [(ngModel)]="contact.phone" [pattern]="phonePattern" placeholder="Enter Phone Number" />

Here the [pattern] binding doesn't seem to be working.. Any idea?

In my .ts ponent file, I've a variable like (to restrict an invalid phone number being entered),

public phonePattern = ^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$;

And in my ponent html file, I've a text box declared as,

<input type="text" [(ngModel)]="contact.phone" [pattern]="phonePattern" placeholder="Enter Phone Number" />

Here the [pattern] binding doesn't seem to be working.. Any idea?

Share Improve this question edited May 10, 2018 at 12:11 David R asked May 10, 2018 at 11:56 David RDavid R 15.7k8 gold badges58 silver badges74 bronze badges 5
  • Why don't you use a custom validator with that Regex? – Niladri Commented May 10, 2018 at 12:10
  • 2 @Niladri, Yes I can!. But just curious to know why this particular way doesn't give me the result. :-) – David R Commented May 10, 2018 at 12:11
  • see this – Vikas Commented May 10, 2018 at 12:54
  • Can you give an example of what you consider a valid phone number? – Martin Parenteau Commented May 10, 2018 at 13:24
  • 1 Exactly my problem, why does Angular not take into account a regex with validation. I mean, it is not that I put a regex for fun in there? Why do I have to do it in the ponent? And why is [pattern] not binding indeed? Is this a bug in newer versions or is it by design? – Michelangelo Commented May 22, 2019 at 14:24
Add a ment  | 

4 Answers 4

Reset to default 2

Try initializing the regex like this:

phonePattern = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;

And do verify whether your regex pattern is correct or not.

Use Model driven forms it has inbuilt methods to validate regular expressions.

import { FormGroup, FormControl, Validators } from '@angular/forms';
.
.
.
class ModelFormComponent implements OnInit {
  myform: FormGroup;

  ngOnInit() {
    myform = new FormGroup({
        name: new FormGroup({
            firstName: new FormControl('', Validators.required), 
            lastName: new FormControl('', Validators.required),
        }),
        email: new FormControl('', [ 
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*") 
        ]),
        password: new FormControl('', [
            Validators.minLength(8), 
            Validators.required
        ]),
        language: new FormControl() 
    });
  }
}

here is sample of model driven form model driven forms

Well what I ended up doing is something like this, in the ponent:

number;
matchesRegex; //Define method

  ngOnInit() {
    //set method
    this.matchesRegex = function () {
      if (this.number === null) {
        return false;
      }
      return this.number.match(/^-?[1-9]?\d[,]-?[1-9]?\d$/gm);
    }
  }

Then in my HTML template:

<input [(ngModel)]="number" [ngClass] = "{'is-valid': matchesRegex()}">

This works wonderfully since it is checked every cycle and your value is updated when the user types. You can use this to block submission or disable a button or whatever. I just used it for a class. The native validator stops you from submitting an invalid pattern.

Create a phone validation directive.

import { Directive } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[phone]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: PhoneDirective, multi: true }
  ]
})
export class PhoneDirective implements Validator {
  constructor() {}

  validate(c: AbstractControl): { [key: string]: any } {
    if (c.value && !/^-?[1-9]?\d[,]-?[1-9]?\d$/gm.test(c.value)) {
      return {
        phone: 'Invalid phone number'
      };
    }

    return null;
  }
}

Now you can just add the phone attribute to your input

<input type="text" [(ngModel)]="contact.phone" phone placeholder="Enter Phone Number" />

本文标签: javascriptWhy does the pattern not working in Angular 5Stack Overflow