如何在Angular 2表单中添加更多的Validator参数

时间:2016-10-10 19:58:12

标签: validation angular typescript angular2-forms

我尝试将多个角度验证器参数[即Validators.minLength(8)和Validators.maxLength(12)]添加到我的表单中,我似乎无法使其工作......这些参数附加到(密码和密码c)实例在下面的代码中。有什么帮助吗?

   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]
            });

        }
    }

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:-1)

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

这应该适合你。