Joh*_*oge 7 asp.net asp.net-mvc
在阅读ScottGU关于该主题的博客文章后,我一直在修改ASP.net MVC中的客户端验证功能.使用System.Componentmodel.DataAnnotations属性非常容易,如下所示:
[Required(ErrorMessage = "You must specify a reason")]
public string ReasonText { get; set; }
Run Code Online (Sandbox Code Playgroud)
......但是如果你需要一些更复杂的东西会发生什么.如果您的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
Run Code Online (Sandbox Code Playgroud)
接下来,您需要实现验证器类.该类负责让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
Run Code Online (Sandbox Code Playgroud)
现在您可以在应用程序启动方法中注册所有内容Global.asax
:
DataAnnotationsModelValidatorProvider.RegisterAdapter(GetType(RequiredIfAttribute), GetType(RequiredIfValidator))
Run Code Online (Sandbox Code Playgroud)
这可以让你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));
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助,这对于工作来说真的很痛苦.
归档时间: |
|
查看次数: |
2600 次 |
最近记录: |