且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在用户离开字段后验证字段

更新时间:2023-12-01 20:02:22

Angular 1.3现在拥有ng-model-options,您可以例如,将选项设置为 {'updateOn':'blur'} ,并且甚至可以消除使用输入速度太快或者想要保存很少昂贵的DOM操作(例如模型写入多个DOM位置,并且您不希望每个关键点都发生$ digest循环)



https://docs.angularjs.org/guide/forms#custom-triggers https://docs.angularjs.org/guide/forms#non-immediate -bounced-model-updates


默认情况下,对内容的任何更改都会触发模型更新并
表单验证。您可以使用
ngModelOptions伪指令来覆盖此行为,以仅绑定到指定的事件列表。
I.e. ng-model-options ={updateOn:'blur'}只会在控件失去焦点后更新并验证
。您可以使用
空格分隔列表设置多个事件。即ng-model-options ={updateOn:'mousedown
blur'}


并且反弹


您可以使用debounce键
和ngModelOptions指令来延迟模型更新/验证。这种延迟也适用于
分析器,验证器和模型标志,如$ dirty或$ pristine。



I。在触发模型更新和
表单验证之前,ng-model-options ={debounce:500}将等待自上次内容更改以来的半个月



With AngularJS, I can use ng-pristine or ng-dirty to detect if the user has entered the field. However, I want to do client-side validation only after the user has left the field area. This is because when a user enters a field like e-mail or phone, they will always get an error thrown until they've completed typing out their full e-mail, and this is not an optimal user experience.

Example


UPDATE:

Angular now ships with a custom blur event: https://docs.angularjs.org/api/ng/directive/ngBlur

Angular 1.3 now has ng-model-options, and you can set the option to { 'updateOn': 'blur'} for example, and you can even debounce, when the use is either typing too fast, or you want to save a few expensive DOM operations (like a model writing to multiple DOM places and you don't want a $digest cycle happening on every key down)

https://docs.angularjs.org/guide/forms#custom-triggers and https://docs.angularjs.org/guide/forms#non-immediate-debounced-model-updates

By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options="{ updateOn: 'blur' }" will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options="{ updateOn: 'mousedown blur' }"

And debounce

You can delay the model update/validation by using the debounce key with the ngModelOptions directive. This delay will also apply to parsers, validators and model flags like $dirty or $pristine.

I.e. ng-model-options="{ debounce: 500 }" will wait for half a second since the last content change before triggering the model update and form validation.