2017-02-22 59 views
8

我想验证输入类型=“文本”使用模式,我只想要文本。Angular 2:Validators.pattern()不工作

组件:

this.from = this.fb.group({ 
    name: ['',[Validators.required,Validators.pattern('/^[a-zA-Z]+$/')]], 

}); 

HTML:

<input type="text" formControlName="name"/> // omitting other html template like from tag. 

上面的图案验证工作不适合我,它总是会返回无效状态。

+2

如果你确实传递了一个正则表达式,而不是字符串:'pattern(/^[a-zA-Z] + $ /)'会发生什么? –

+1

或者Validators.pattern('^ [a-zA-Z] + $')' –

+0

谢谢@GünterZöchbauerValidators.pattern('^ [a-zA-Z] + $')工作。 –

回答

12

通过模式为字符串,不/这对正则表达式的分隔符

Validators.pattern('^[a-zA-Z]+$') 
+0

'pin_code':['',[ Validators.required, Validators.pattern('^ [0-9] {1,6} $') ]], – AlpeshVasani

+0

REGEXP无法正常工作, 4个项目...只需要从安慰条件下工作 – AlpeshVasani

6
emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; 
this.form = fb.group({ 
     Email : new FormControl({value: null}, Validators.compose([ 
     Validators.required, 
     Validators.pattern(this.emailRegex)])) 
}); 
3

这是我发现使用Validators.pattern()时:

作品

Validators.pattern('[a-z]{2}') 
Validators.pattern(/^[a-z]{2}$/) 

不工作

Validators.pattern(/[a-z]{2}/i) 
Validators.pattern(/[a-z]{2}/) 
+0

谢谢,工作.... –

0

请记住,不能做到这一点:

Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}") 

的疑难杂症是,你需要在s前面一个双反斜线打败这样的字符串逃脱

Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\\s?[0-9][A-Z]{2}")