jQuery.validator.unobtrusive.adapters.addMinMax round trips, doesn't work in MVC3
回答
Solved! I forgot/didn't understand that you have to pass jQuery itself into the function closure. Therefore the custom validator on the client side should look like this:
需要注意的是,仅有addMethod是无法成功添加rule的,还必须配合后面的adapter.add来确保生效
$(function () {
jQuery.validator.addMethod('dayRange', function (value, element, param) {
if (!value) return false;
var valueDateParts = value.split(param.seperator);
var minDate = new Date();
var maxDate = new Date();
var now = new Date();
var dateValue = new Date(valueDateParts[2],
(valueDateParts[1] - 1),
valueDateParts[0],
now.getHours(),
now.getMinutes(),
(now.getSeconds()+5));
minDate.setDate(minDate.getDate() - parseInt(param.min));
maxDate.setDate(maxDate.getDate() + parseInt(param.max));
return dateValue >= minDate && dateValue <= maxDate;
});
jQuery.validator.unobtrusive.adapters.add('dayrange', ['min', 'max', 'dateseperator'], function (options) {
var params = {
min: options.params.min,
max: options.params.max,
seperator: options.params.dateseperator
};
options.rules['dayRange'] = params;
if (options.message) {
options.messages['dayRange'] = options.message;
}
});
}(jQuery));
如果是简单的,可以这么写,如果仅仅是一个返回Bool值的rule的话。
jQuery.validator.addMethod('checkName', function (value, element, param) {
var userName = "@employee.MemberLogin".toLowerCase();
var name = "@employee.FirstName".toLowerCase();
var surname = "@employee.LastName".toLowerCase();
var password = value;
var DoesContainFirstName = name.length > 0 && password.toLowerCase().indexOf(name) !== -1;
var DoesContainLastName = surname.length > 0 && password.toLowerCase().indexOf(surname) !== -1;
var DoesContainUserName = userName.length > 0 && password.toLowerCase().indexOf(userName) !== -1;
if (!DoesContainFirstName && !DoesContainLastName && !DoesContainUserName) {
return true;
}
return false;
});
jQuery.validator.unobtrusive.adapters.addBool("checkName");
完全自定义的话,可以这么写,核心是调用 that.unobtrusive("newp"); 自己封装的函数,里面会调用$.validator.unobtrusive.adapters.add方法
setNewPassword() {
let that = this;
$.validator.addMethod("newp", function(value, element, params) {
let reg =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]).{10,50}$/;
if (!value) {
return true;
}
if (reg.test(value)) {
var password = value.toLowerCase();
if (
password.indexOf(that.userInfo.FirstName.toLowerCase()) == -1 &&
password.indexOf(that.userInfo.LastName.toLowerCase()) == -1 &&
password.indexOf(that.userInfo.MemberLogin.toLowerCase()) == -1
) {
return true;
}
return false;
}
});
that.unobtrusive("newp");
},
unobtrusive(code) {
$.validator.unobtrusive.adapters.add(code, ["va"], function(options) {
options.rules[code] = {
va: options.params.va
};
options.messages[code] = options.message;
});
},