【问题标题】:Angular2 validate form only on certain conditionsAngular2 仅在特定条件下验证表单
【发布时间】:2017-01-27 03:54:42
【问题描述】:

我想只在创建过程中对用户表单进行验证,而不是更新

这是我的验证逻辑

    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 变量为真时,所以我尝试过

    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

【问题讨论】:

  • this.newUser 设置在哪里?
  • 尝试通过 null 而不是 "" : this.newUser ? Validators.compose(...) : null

标签: angular typescript


【解决方案1】:

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

或者

你最初可以设置:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 此表单用于用户故事 crud 操作,创建用户时使用默认密码,但管理员在更新用户凭据时可以更新密码或更新密码失败,因此密码为在更新期间不是强制性的,但在创建期间是强制性的......希望它有意义
    • 有道理!在这种情况下,请查看此帖子:stackoverflow.com/questions/40404485/…
    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多