2016-10-10 42 views
0

我已经尝试在我的表单中添加多个角度验证器参数[即Validators.minLength(8)和Validators.maxLength(12)],我似乎无法得到它工作......这些参数被附加到下面代码中的(password和passwordc)实例。请帮忙吗?我如何在Angular 2表单中添加更多的Validator参数

export class signupComponent { 
     signupform: FormGroup; 
     constructor(public fb: FormBuilder) { 
      this.signupform = this.fb.group({ 
       firstname: ['', Validators.required], 
       lastname: ['', Validators.required], 
       account: this.fb.group({ 
        email: ['', Validators.required], 
        **password: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')], 
        passwordc: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')], 
       }, { validator: passwordMatcher }),** 
       shortbio: ['', Validators.required] 
      }); 

     } 
    } 

回答

1

要支持多个验证器,您必须使用接受验证器数组的Validator.compose([])方法。你的情况:

password: ['', Validators.compose([Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')])] 
+2

以前是这样,但不再是(IIRC:RC3或RC4)。现在,您可以简单地传递一个验证器数组 - 您不再需要'Validators.compose()'。然而,'Validator.compose()'*仍然可以被使用,所以我认为你的答案会解决这个问题。 – BlueM

-1
password: ['', [Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')]] 

这应该为你做的工作。

+0

这与其他答案**非常相似。我认为它应该是对另一个答案的评论,而不是一个单独的答案。 – MSeifert

+0

相似但不相同。我已经省略了“撰写”。没有必要。我简化了它。 – Mano

+0

是的,这也是[已经提到](http://stackoverflow.com/questions/39965847/how-do-i-add-more-that-one-validator-argument-in-angular-2-form/42634393 ?noredirect = 1#comment67223310_39966100),对吧? – MSeifert

相关问题