敲除验证在加载时立即评估 [英] Knockout Validation evaluates immediately on load

查看:11
本文介绍了敲除验证在加载时立即评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVC、Knockout 和 Knockout 验证来验证我的视图模型.

I'm using MVC, Knockout, and Knockout Validation to validate my view model.

我遇到了一个问题,即在加载时立即触发对视图模型属性的验证.换句话说,在用户尝试更改其值之前,我的输入旁边会显示此字段为必填字段".

I'm running into an issue where the validation for view model properties are firing immediately upon loading. In other words, "This field is required" shows up next to my inputs before a user has attempted to change their values.

这个问题特别发生在下拉(选择)控件上.

This problem is specifically happening with dropdown (select) controls.

我猜这是我在无意中更改/访问/改变我的 javascript 代码另一部分中的 observable 造成的问题.但是,我不知道如何追踪.

I'm guessing that this is a problem that I've created by somehow unintentionally changing/accessing/mutating the observable in another part of my javascript code. However, I don't know how to track this down.

有没有一种方法可以让我以某种方式订阅或跟踪导致 Knockout 验证中验证的事件?我只需要知道为什么会这样.我非常确信 isValid() 函数的值始终为 false.

Is there a way that I can somehow subscribe or track the even that fires that causes validation in Knockout Validation? I just need to know why this is firing in the way it is. I'm pretty confident that the value of the isValid() function is consistently false.

以下是我的 HTML 在页面加载时设置的示例,不受干扰:

Here's a sample of how my HTML is setup on page load, unmolested:

<select class="highlightable validationElement" name="obsstate" data-bind="value: standardAnswers.ans106_1.value" required="true">
    <option value="">-- Select -- </option>
        <option value="AK">AK</option>
        <option value="AL">AL</option>
        etc...

</select>

推荐答案

我自己解决了这个问题.

I figured out this issue on my own.

问题存在于 razor 引擎模板化选择选项,然后将所选元素的值绑定到 Knockout.

The problem exists between the razor engine templating the select options, and then later binding the value of the selected element to Knockout.

尽管选择框中没有用户输入的值,默认值,--select--"实际上包含一个值.就我而言,它是一个空字符串.因此,当我应用淘汰绑定时,我的 viewmodel 属性被更新"为空字符串值,因此验证被触发.

Despite the fact that there is no user-inputted value in the select box, the default value, the "--select--" actually contains a value. In my case it was an empty string. Therefore, when I applied the knockout bindings, my viewmodel property was "updated" with the empty string value, and therefore validation fired.

为了解决这个问题,我将模型的默认值设置为空字符串.因此,当应用绑定时,不会在 Knockout observable 上触发 valueHasMutated 事件,因此不会进行验证.

To get around this in my case I set the default value of my model to be an empty string. Therefore when the bindings are applied, there is no valueHasMutated event fired on the Knockout observable, and thus no validation.

这篇关于敲除验证在加载时立即评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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