Aurelia validation: applying some rule on change and some on blur on same property

天涯浪子 提交于 2019-12-13 15:57:31

问题


I have an input field for a value that should have exactly 5 digits. I would like to show errors when typing characters other than digits immediatly (onChange) but showing the error for unsufficient string length only on blur.

My rule looks like so at the moment:

ValidationRules
    .ensure("myInput")
    .matches(new RegExp(/[0-9]/))
    .minLength(5)
    .on(this);

MaxLength is restricted by setting maxlength in html.

If I set the validation trigger to "onChange" to get an immediate response to wrong characters I also get an error shown for not satisfying the minLength rule while typing correct digits until having typed 5 of them.

The behavior I would like to have is to apply the matches-rule onChange and the minLength-rule onBlur.

Is there any possibility to apply two rules on the same property on different events? I know how to validate manually but I don't know how to differenciate between rules.


回答1:


You can use the when fluent API to satisfy your needs. Something like this -

ValidationRules
  .ensure('email')
    .email()
    .required()
      .when((order) => {
        if (order.length > 4) {
          order._ruleHasBeenMet = true;
        }
        return order.length > 4 && order._ruleHasBeenMet;
      }
      .withMessage('Email is required when shipment notifications have been requested.');



回答2:


Encouraged by @PWKad's answer I played a little with .when() and came up with this:

I changed the validate trigger to "validateOnChangeAndBlur" and added a reference to my field:

<input type="text" value.bind="myInput & validateOnChangeAndBlur" maxlength="5" ref="myInputRef">

I extended the validation rule with a conditional validation checking if my input has focus as I only want to validate length when the input loses focus:

ValidationRules
  .ensure("myInput")
  .matches(new RegExp(/[0-9]/))
  .minLength(5)
    .when(() => this.dwKapitel !== document.activeElement)
  .on(this);

This works like I expect it to work.



来源:https://stackoverflow.com/questions/41137697/aurelia-validation-applying-some-rule-on-change-and-some-on-blur-on-same-proper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!