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

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

问题描述

我正在使用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代码另一部分中的可观察对象的值,从而造成了这个问题.但是,我不知道该如何追踪.

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 Validation中引发验证的事件?我只需要知道为什么会这样触发.我非常有信心isValid()函数的值始终为假.

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.

剃刀引擎将选择选项模板化,然后再将所选元素的值绑定到敲除之间,就会出现问题.

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上触发任何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天全站免登陆