Angular2仅在某些条件下验证表单

时间:2017-01-27 03:54:43

标签: angular typescript

我想仅在创建期间而不是更新

来复制用户表单

这是我的验证逻辑

    this.userform = this._formbuilder.group({
  first_name: ['', Validators.required],
  last_name: ['', Validators.required],
  username: ['', Validators.compose(
    [
      Validators.required,Validators.minLength(5)
    ]
  )],
  password: ['',Validators.compose([
    Validators.required,ValidationService.passwordValidator
  ])],
  email: ['', Validators.compose([
    Validators.required,ValidationService.emailValidator
  ])],
  role: ['', Validators.required],

})

我想在创建期间验证密码,即newuser变量为true,所以我已经尝试了

    this.userform = this._formbuilder.group({
  .....

  password: ['',

       (this.newUser) ?Validators.compose([
          Validators.required,ValidationService.passwordValidator
          ]):"" 

       ],
....
})

以上操作失败并返回错误

rror: Error in ./UsersComponent class UsersComponent - inline  
    template:113:51 caused by: 
   v is not a function
   Error: Error in ./UsersComponent class UsersComponent -
     inline template:113:51 caused by: v is not a function

2 个答案:

答案 0 :(得分:1)

您可以创建custom validator,以编程方式检查是否需要,如果passwordValidator可用则调用this.user将其设置为唯一的验证器。

或者

您最初可以设置:

  this.userform = this._formbuilder.group({
  .....

  password: [''] //no initial validators,
....
})

this.newUser设置为true的函数中,使用setControl

this.userform.setControl("password",new FormControl('',Validators.compose([
          Validators.required,ValidationService.passwordValidator
          ]));

答案 1 :(得分:0)

为什么您不希望在用户更改其个人资料时验证表单?这意味着用户在更新其个人资料后可以没有用户名,没有密码,也没有电子邮件?这不是逻辑。