简体   繁体   English

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

[英]Angular2 validate form only on certain conditions

I would like to vlidate a user form only during create but not update 我只想在创建过程中创建用户表单,而不更新

This is my validation logic 这是我的验证逻辑

    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],

})

I would like to validate the password only during create that is when the newuser variable is true so ive tried 我只想在newuser变量为true的创建期间验证密码,所以我尝试了

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

  password: ['',

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

       ],
....
})

The above fails an returns an error 以上失败返回错误

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

You can create a custom validator where you programmatically check for required and call passwordValidator if this.user is available set it as the only validator. 您可以创建一个自定义验证器 ,在其中以编程方式检查是否需要验证器 ,如果this.user可用,则调用passwordValidator ,将其设置为唯一验证器。

Or 要么

You could initially set: 您可以最初设置:

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

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

and in the function where this.newUser is set to true ,use setControl this.newUser设置为true的函数中,使用setControl

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

Why you don't want to validate the form when a user what to change his profile? 当用户更改个人资料时,为什么不想验证表单? That means that a user can, after an update of his profile, have no username, no password and no email? 这意味着用户在更新其个人资料后可以没有用户名,密码和电子邮件吗? It's not logic. 这不是逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM