javascript - Jquery Unobtrusive Validation 'Cannot read property ' 类型“未定义”

标签 javascript jquery jquery-validate unobtrusive-validation

我在我的 MVC 应用程序中使用 jQuery Unobtrusive Validation。发回时,验证按规定进行。但是,我有充分的理由阻止客户端回发。

我遵循在多个站点上看到的规定方法......并且我尝试了许多不同的组合。但是,我仍然不断收到以下错误:

"Cannot read property 'type' of undefined"

我的 JavaScript 看起来像:
当我调用“showErrors”时发生错误...

function onValidateCity(e){

    // Checks the value of my Kendo Combobox
    var value = this.value();
    if (value && this.selectedIndex === -1) {

        // Yes, it reaches this part
        var validator = $('#CityId').validate();
        validator.showErrors({"CityId": "My custom error message!"});
    }
}

我的 MVC 助手创建以下 HTML:

<span class="k-widget k-combobox k-header form-control">
    <span tabindex="-1" unselectable="on" class="k-dropdown-wrap k-state-default">
        <input name="CityId_input" class="k-input form-control" type="text" autocomplete="off" title="" maxlength="524288" role="combobox" aria-expanded="false" placeholder="-- Select City --" tabindex="0" aria-disabled="false" aria-readonly="false" aria-autocomplete="list" aria-owns="CityId_listbox" aria-busy="false" style="width: 100%;" /> 
        <span tabindex="-1" unselectable="on" class="k-select">
            <span unselectable="on" class="k-icon k-i-arrow-s" role="button" tabindex="-1" aria-controls="CityId_listbox">select</span>
        </span>
    </span>
    <input autocomplete="off" class="form-control" data-val="true" data-val-required="The City field is required." id="CityId" name="CityId" type="text" value=  "28dbddea-660d-4bbb-b063-f926b1153866" data-role="combobox" aria-disabled="false"
aria-readonly="false" novalidate="novalidate" style="display: none;" />
</span>

<span class="field-validation-valid text-danger" data-valmsg-for="CityId" data-valmsg-replace="true"></span>

MVC(验证)助手看起来像:
@Html.ValidationMessageFor(model => model.CityId, "", new { @class = "text-danger"})

最佳答案

当您初始化 validator 时,请针对包含嵌套在其中的 CityId 输入的元素(而不是输入元素本身)执行此操作。它可以是 formdivspan

这是在 fiddle 中工作的简化代码,我是针对 span 完成的: <强> http://jsfiddle.net/o0qhcbbL/1/

$('#button').click(function (e) {
    onValidateCity(e)
})

function onValidateCity(e) {

    var validator = $('#xx').validate();

    validator.showErrors({
        "CityId": "My custom error message!"
    });
}

html:

<span id="xx">
    <input id="CityId" name="CityId" type="text" />
</span>
<span id="button">select</span>

关于javascript - Jquery Unobtrusive Validation 'Cannot read property ' 类型“未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895359/

相关文章:

css - 当 jQuery 验证插件中的表单有效时,如何设置错误样式(具有良好的填充)并使错误容器消失?

javascript - 简单的 CSS 过渡

javascript - 如何使用 JavaScript 拦截 HTML5 输入验证?

JQuery 循环幻灯片重叠

jquery - Bootstrap 表单验证

javascript - ModelClientValidationRule ValidationType 字符串的有效值?

javascript - Angularjs教程第7步;无法看到动态创建的列表

javascript - HTML5 距离回调的地理定位

javascript - 为什么这段代码会在 "strict mode"中抛出 undefined

javascript - 如何在 JavaScript 中获取字符串表示的参数数组