创建了一个自定义验证属性,我也想让它在客户端工作。这是Model类
public class CreditCardAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
var number = Convert.ToString(value);
return IsValidNumber(number);
}
private bool IsValidNumber(string number)
{
int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 };
int checksum = 0;
char[] chars = number.ToCharArray();
for (int i = chars.Length - 1; i > -1; i--)
{
int j = ((int)chars[i]) - 48;
checksum += j;
if (((i - chars.Length) % 2) == 0)
checksum += DELTAS[j];
}
return ((checksum % 10) == 0);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule {
ErrorMessage = this.ErrorMessage,
ValidationType = "CreditCard"
};
}
}
jQuery的:
jQuery.validator.addMethod('CreditCardtest', function (value, element, params)
{
return false;
});
jQuery.validator.unobtrusive.adapters.add('CreditCard', { }, function(options){
options.rules['CreditCardtest'] = true;
options.messages['CreditCardtest'] = options.message;
});
我不确定应该去CreditCardTest,我想在这里重写模型中的内容吗?
谢谢
答案 0 :(得分:4)
验证信用卡号可能是您不希望为其实现客户端验证的内容。
但是如果您对如何在一般情况下实现它感兴趣,则必须在javascript中实现与服务器上相同的逻辑。
您的自定义验证属性只有一个问题,这是验证类型的名称,它必须只包含小写字母:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "creditcard" // this should be only lowercase letters
};
}
一旦我们修复了,我们就可以在客户端上实现相同的验证逻辑:
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
var isValidNumber = function (value, element, params) {
var DELTAS = [0, 1, 2, 3, 4, -4, -3, -2, -1, 0];
var checksum = 0;
for (var i = value.length - 1; i > -1; i--) {
var j = value.charCodeAt(i) - 48;
checksum += j;
if (((i - value.Length) % 2) == 0) {
checksum += DELTAS[j];
}
}
return (checksum % 10) == 0;
};
jQuery.validator.addMethod('CreditCardtest', isValidNumber);
jQuery.validator.unobtrusive.adapters.add('creditcard', { }, function (options) {
options.rules['CreditCardtest'] = true;
options.messages['CreditCardtest'] = options.message;
});
</script>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Number)
@Html.ValidationMessageFor(x => x.Number)
<button type="submit">OK</button>
}
显然,所有脚本都会进入一个单独的文件而不是视图内部。我把它留在这里是为了更容易阅读。
答案 1 :(得分:1)
是的,如果要验证客户端,则需要编写服务器端验证代码的JavaScript版本。 (因为这是问的问题,是时候回家了。)