我已经使用jquery验证插件几年了,但这是我第一次尝试混合使用MVC 3不显眼的验证。
事情的客户端信息分散在互联网上,很难找到足够深刻的东西来解释尚未使用的人。我一直在燃烧Google一小时,以了解如何创建自定义客户端验证器的示例。
@Html.TextBoxFor(model => Model.CCPayment.CardNumber,new { @class = "textInput validateCreditCard",maxLength = "20" }) $(document).ready(function () { jQuery.validator.unobtrusive.adapters.add('validateCreditCard',{},function (value,element) { alert('foo'); }); });
如果我在我的视图底部运行上面的代码,它绝对没有。我甚至尝试过jquery.validator.addmethod(),但仍然没有。从我的模型验证注释发出的所有客户端验证工作正常。
<div class="ctrlHolder"> <label> <em>*</em> Card Number: </label> @Html.TextBoxFor(model => Model.CCPayment.CardNumber,maxLength = "20" }) <p class="field-validation-valid formHint" data-valmsg-for="CCPayment.CardNumber"></p> </div>
解决方法
以下是您可以继续的方法。首先,您需要编写自定义验证器属性,以确保在服务器端执行验证。你可以使用这个
blog post描述的那个:
public class CreditCardAttribute : ValidationAttribute,IClientValidatable { private CardType _cardTypes; public CardType AcceptedCardTypes { get { return _cardTypes; } set { _cardTypes = value; } } public CreditCardAttribute() { _cardTypes = CardType.All; } public CreditCardAttribute(CardType AcceptedCardTypes) { _cardTypes = AcceptedCardTypes; } public override bool IsValid(object value) { var number = Convert.ToString(value); if (String.IsNullOrEmpty(number)) return true; return IsValidType(number,_cardTypes) && IsValidNumber(number); } public override string FormatErrorMessage(string name) { return "The " + name + " field contains an invalid credit card number."; } public enum CardType { Unknown = 1,Visa = 2,MasterCard = 4,Amex = 8,Diners = 16,All = CardType.Visa | CardType.MasterCard | CardType.Amex | CardType.Diners,AllOrUnknown = CardType.Unknown | CardType.Visa | CardType.MasterCard | CardType.Amex | CardType.Diners } private bool IsValidType(string cardNumber,CardType cardType) { // Visa if (Regex.IsMatch(cardNumber,"^(4)") && ((cardType & CardType.Visa) != 0)) return cardNumber.Length == 13 || cardNumber.Length == 16; // MasterCard if (Regex.IsMatch(cardNumber,"^(51|52|53|54|55)") && ((cardType & CardType.MasterCard) != 0)) return cardNumber.Length == 16; // Amex if (Regex.IsMatch(cardNumber,"^(34|37)") && ((cardType & CardType.Amex) != 0)) return cardNumber.Length == 15; // Diners if (Regex.IsMatch(cardNumber,"^(300|301|302|303|304|305|36|38)") && ((cardType & CardType.Diners) != 0)) return cardNumber.Length == 14; //Unknown if ((cardType & CardType.Unknown) != 0) return true; return false; } 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" }; } }
请注意,我修改了它,使其实现了IClientValidatable
接口,并添加了GetClientValidationRules
方法,该方法只是使用相同的错误消息进行客户端验证作为服务器端,并为该验证器提供了一个唯一的名称,该名称将由jquery unobtrusive适配器使用。现在剩下的是用这个属性来装饰你的模型属性:
[CreditCard(ErrorMessage = "Please enter a valid credit card number")] [required] public string CardNumber { get; set; }
在你看来:
<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"> $(function () { jQuery.validator.unobtrusive.adapters.addBool('creditcard'); }); </script> @using (Html.BeginForm()) { @Html.TextBoxFor(x => x.CardNumber) @Html.ValidationMessageFor(x => x.CardNumber) <input type="submit" value="OK" /> }