在阅读了有关该主题的
ScottGU’s blog post之后,我一直在修改ASP.net MVC中的客户端验证功能.使用System.Componentmodel.DataAnnotations属性非常容易,如下所示:
[required(ErrorMessage = "You must specify a reason")] public string ReasonText { get; set; }
……但是如果你需要一些更复杂的东西会发生什么.如果您的Address类具有PostalCode和CountryCode字段,该怎么办?您可能希望根据每个国家/地区的不同正则表达式验证邮政编码. [0-9] {5}适用于美国,但加拿大需要另外一个.
我通过滚动自己的ValidationService类来解决这个问题,该类接受控制器的ModelState属性并相应地验证它.这在服务器端运行良好,但不适用于新的客户端验证.
在Webforms中,我会使用像JavaScript一样的控件,如requiredFieldValidator或CompareValidator,然后使用CustomValidator来处理复杂的规则.这样我就可以在一个地方拥有所有的验证逻辑,并且我可以获得快速javascript验证的好处(90%的时间),同时我仍然可以获得服务器端验证的安全性作为支持.
MVC中的等效方法是什么?
解决方法
编辑:这假设您正在使用MVC 3.不幸的是我的代码是在VB.NET中,因为这是我在工作中必须使用的.
为了使一切都能很好地与新的不显眼的验证相结合,您需要做一些事情.几个星期前我通过它们.
首先,创建一个继承自ValidationAttribute的自定义属性类.一个简单的requiredIf属性类如下:
Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations <AttributeUsage(AttributeTargets.Field Or AttributeTargets.Property,AllowMultiple:=False,Inherited:=False)> _ Public NotInheritable Class requiredIfAttribute Inherits ValidationAttribute Private Const _defaultErrorMessage As String = "'{0}' is required." Private ReadOnly _dependentProperty As String Private ReadOnly _targetValues As Object() Public Sub New(dependentProperty As String,targetValues As Object()) MyBase.New(_defaultErrorMessage) _dependentProperty = dependentProperty _targetValues = targetValues End Sub Public Sub New(dependentProperty As String,targetValues As Object(),errorMessage As String) MyBase.New(errorMessage) _dependentProperty = dependentProperty _targetValues = targetValues End Sub Public ReadOnly Property DependentProperty() As String Get Return _dependentProperty End Get End Property Public ReadOnly Property TargetValues() As Object() Get Return _targetValues End Get End Property Public Overrides Function FormatErrorMessage(name As String) As String Return String.Format(Globalization.CultureInfo.CurrentUICulture,ErrorMessageString,name) End Function Protected Overrides Function IsValid(value As Object,context As ValidationContext) As ValidationResult ' find the other property we need to compare with using reflection Dim propertyValue = context.ObjectType.GetProperty(DependentProperty).GetValue(context.ObjectInstance,Nothing).ToString() Dim match = TargetValues.SingleOrDefault(Function(t) t.ToString().ToLower() = propertyValue.ToLower()) If match IsNot Nothing AndAlso value Is Nothing Then Return New ValidationResult(FormatErrorMessage(context.DisplayName)) End If Return Nothing End Function End Class
接下来,您需要实现验证器类.该类负责让MVC知道不显眼的验证库工作所需的客户端验证规则.
Public Class requiredIfValidator Inherits DataAnnotationsModelValidator(Of requiredIfAttribute) Public Sub New(MetaData As ModelMetadata,context As ControllerContext,attribute As requiredIfAttribute) MyBase.New(MetaData,context,attribute) End Sub Public Overrides Function GetClientValidationRules() As IEnumerable(Of ModelClientValidationRule) Dim rule As New ModelClientValidationRule() With {.ErrorMessage = ErrorMessage,.ValidationType = "requiredif"} rule.ValidationParameters("dependentproperty") = Attribute.DependentProperty.Replace("."c,HtmlHelper.IdAttributeDotReplacement) Dim first As Boolean = True Dim arrayString As New StringBuilder() For Each param In Attribute.TargetValues If first Then first = False Else arrayString.Append(",") End If arrayString.Append(param.ToString()) Next rule.ValidationParameters("targetvalues") = arrayString.ToString() Return New ModelClientValidationRule() {rule} End Function End Class
现在,您可以在Global.asax的应用程序启动方法中注册所有内容:
DataAnnotationsModelValidatorProvider.RegisterAdapter(GetType(requiredIfAttribute),GetType(requiredIfValidator))
这可以让你90%的方式.现在您只需要告诉JQuery validate和MS不显眼的验证层如何读取您的新属性:
/// <reference path="jquery-1.4.1-vsdoc.js" /> /// <reference path="jquery.validate-vsdoc.js" /> /* javascript for custom unobtrusive validation ==================================================== */ (function ($) { // this adds the custom "requiredif" validator to the jQuery validate plugin $.validator.addMethod('requiredif',function (value,element,params) { // the "value" variable must not be empty if the dependent value matches // one of the target values var dependentVal = $('#' + params['dependentProperty']).val().trim().toLowerCase(); var targetValues = params['targetValues'].split(','); // loop through all target values for (i = 0; i < targetValues.length; i++) { if (dependentVal == targetValues[i].toLowerCase()) { return $.trim(value).length > 0; } } return true; },'not used'); // this tells the MS unobtrusive validation layer how to read the // HTML 5 attributes that are output for the custom "requiredif" validator $.validator.unobtrusive.adapters.add('requiredif',['dependentProperty','targetValues'],function (options) { options.rules['requiredif'] = options.params; if (options.message) { options.messages['requiredif'] = options.message; } }); } (jQuery));
希望这会有所帮助,这对于工作来说真的很痛苦.