MVC3 CompareAttribute, client-side bug

瘦欲@ 提交于 2019-11-27 14:10:44
nemesv

It should work with the [Compare("Password", ErrorMessage = "Passwords do not match.")] attribute but it seems this is really a bug in the jquery.validate.unobtrusive.js file. The problem is in this code:

adapters.add("equalto", ["other"], function (options) {
    var prefix = getModelPrefix(options.element.name),
        other = options.params.other,
        fullOtherName = appendModelPrefix(other, prefix),
        element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];

    setValidationValues(options, "equalTo", element);
});

So it tries to find the other control with the JQuery find method. But the "." dot character is not escaped in the fullOtherName variable (in your case it will contain: "Register.Password") as described in this SO question. That is the reason why it works when you only use RegisterViewModel directly because then there is no dots in the names.

To fix it you need to add one line to the appendModelPrefix function:

//original
function appendModelPrefix(value, prefix) {
    if (value.indexOf("*.") === 0) {
        value = value.replace("*.", prefix);
    }
    return value;
}

//fixed
function appendModelPrefix(value, prefix) {
    if (value.indexOf("*.") === 0) {
        value = value.replace("*.", prefix);
    }
    value = value.split('.').join('\\.');
    return value;
}

Very good answer, nemesv.

Only one thing to add for rookies:

function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}

becomes

function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);a=a.split('.').join('\\.');return a}

in .min.js

Otherwise when you publish, the error comes back.

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