Angular 5 仅对模糊进行验证? [英] Angular 5 solely validation on blur?

查看:17
本文介绍了Angular 5 仅对模糊进行验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在模糊上以反应形式进行验证.目前您可以设置 updateOn: "blur" 但是输入字段的值不会在输入时更新.在我的情况下,我需要在每次击键时更新值,因为我用它进行计算并将结果显示给用户.验证应该只在模糊时发生.

I wonder if it is possible to have the validation in reactive forms on blur. At the moment you can set updateOn: "blur" but then the values of the input fields won't update on input. In my case i need the values to be updated on every keystroke because I do calculations with it and show the result to the user. The validation should only happen on blur.

谢谢.

我使用 FormBuilder,一些内置验证器和一些自定义验证器.示例代码:

I use FormBuilder, some build in validators and some custom validators. Example code:

let formToMake = {
  purpose: [null, Validators.required],
  registrationDate: this.fb.group({
    day: [null, Validators.required],
    month: [null, Validators.required],
    year: [null, Validators.required]
  }),
  isTruth: [null, Validators.compose([checkIfTrue, Validators.required])]
};

如果我要使用模糊事件,我需要手动完成所有验证,我认为这不是一个好方法.

If i would use the blur event i need to do all my validation manually, which i think is not a good way.

推荐答案

我最终做了什么:

使用反应式:

TS

这是要制作的表格.我需要在模糊时验证 productCost 和 LoanAmount,但值本身需要更新 onchange.如果您设置 updateOn: "blur" 验证发生在模糊事件之后,但值将在模糊事件之后更新.

this is the form to make. I needed the productCost and loanAmount to be validated on blur but the values itself needed to update onchange. If you set updateOn: "blur" the validation happens after the blur event but als the values will update after the blur event.

let formToMake = {
      productCost: new FormControl(null, {validators: Validators.required, updateOn: "blur"}),
      loanAmount: new FormControl(null, {validators: Validators.compose([Validators.required, Validators.min(2500)]), updateOn: "blur"}),
      loanLength: new FormControl(49, {validators: Validators.required, updateOn: "change"})
    };

句柄输入法:

为了解决这个问题,我只是做了一个事件处理程序,它将在输入事件上被调用.

To solve this I just made an event handler which will be called on the input event.

TS

handleInput(e: any) {
    this.loanAmount = e;
  }

HTML

<input class="form__input" type="number" value="{{loanForm.get('loanAmount').value}}" id="loanAmount" formControlName="loanAmount" (input)="handleInput($event.target.value)">

这篇关于Angular 5 仅对模糊进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆