我想知道在 ASP.NET MVC 3表单上进行"大于"和"低于"验证的最简单方法是什么?
我使用不显眼的JavaScript进行客户端验证。我有两个 DateTime 属性(StartDate 和 EndDate),我需要验证以确保 EndDate 大于 StartDate。我有另一个类似的案例,在另一种形式上我有一个MinValue(int)和MaxValue(int)。
默认情况下是否存在这种类型的验证?或者有人知道一篇解释如何实现它的文章吗?
可以查看它为int所做的最小/最大
扩展另请查看万无一失的验证,它包括数字/日期时间等的大于比较
您可以简单地通过自定义验证来执行此操作。
[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
public class DateGreaterThanAttribute : ValidationAttribute
{
string otherPropertyName;
public DateGreaterThanAttribute(string otherPropertyName, string errorMessage)
: base(errorMessage)
{
this.otherPropertyName = otherPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
// Using reflection we can get a reference to the other date property, in this example the project start date
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
// Let's check that otherProperty is of type DateTime as we expect it to be
if (otherPropertyInfo.PropertyType.Equals(new DateTime().GetType()))
{
DateTime toValidate = (DateTime)value;
DateTime referenceProperty = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
// if the end date is lower than the start date, than the validationResult will be set to false and return
// a properly formatted error message
if (toValidate.CompareTo(referenceProperty) < 1)
{
validationResult = new ValidationResult(ErrorMessageString);
}
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
// Do stuff, i.e. log the exception
// Let it go through the upper levels, something bad happened
throw ex;
}
return validationResult;
}
}
并在模型中使用它,例如
[DisplayName("Start date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DisplayName("Estimated end date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[DateGreaterThan("StartDate", "End Date end date must not exceed start date")]
public DateTime EndDate { get; set; }
这适用于服务器端验证。对于客户端验证,您可以编写类似 GetClientValidationRules 的方法,例如
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
//string errorMessage = this.FormatErrorMessage(metadata.DisplayName);
string errorMessage = ErrorMessageString;
// The value we set here are needed by the jQuery adapter
ModelClientValidationRule dateGreaterThanRule = new ModelClientValidationRule();
dateGreaterThanRule.ErrorMessage = errorMessage;
dateGreaterThanRule.ValidationType = "dategreaterthan"; // This is the name the jQuery adapter will use
//"otherpropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
dateGreaterThanRule.ValidationParameters.Add("otherpropertyname", otherPropertyName);
yield return dateGreaterThanRule;
}
现在就在眼前
$.validator.addMethod("dategreaterthan", function (value, element, params) {
return Date.parse(value) > Date.parse($(params).val());
});
$.validator.unobtrusive.adapters.add("dategreaterthan", ["otherpropertyname"], function (options) {
options.rules["dategreaterthan"] = "#" + options.params.otherpropertyname;
options.messages["dategreaterthan"] = options.message;
});
您可以在此链接中找到更多详细信息
编写自己的验证器类是否是"最简单的"方法,但这就是我所做的。
用法:
<DataType(DataType.Date)>
Public Property StartDate() As DateTime
<DataType(DataType.Date)>
<DateGreaterThanEqual("StartDate", "end date must be after start date")>
Public Property EndDate() As DateTime
类:
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Property, AllowMultiple:=False, Inherited:=False)>
Public Class DateGreaterThanEqualAttribute
Inherits ValidationAttribute
Public Sub New(ByVal compareDate As String, ByVal errorMessage As String)
MyBase.New(errorMessage)
_compareDate = compareDate
End Sub
Public ReadOnly Property CompareDate() As String
Get
Return _compareDate
End Get
End Property
Private ReadOnly _compareDate As String
Protected Overrides Function IsValid(ByVal value As Object, ByVal context As ValidationContext) As ValidationResult
If value Is Nothing Then
' no need to do or check anything
Return Nothing
End If
' find the other property we need to compare with using reflection
Dim compareToValue = Nothing
Dim propAsDate As Date
Try
compareToValue = context.ObjectType.GetProperty(CompareDate).GetValue(context.ObjectInstance, Nothing).ToString
propAsDate = CDate(compareToValue)
Catch
Try
Dim dp As String = CompareDate.Substring(CompareDate.LastIndexOf(".") + 1)
compareToValue = context.ObjectType.GetProperty(dp).GetValue(context.ObjectInstance, Nothing).ToString
propAsDate = CDate(compareToValue)
Catch
compareToValue = Nothing
End Try
End Try
If compareToValue Is Nothing Then
'date is not supplied or not valid
Return Nothing
End If
If value < compareToValue Then
Return New ValidationResult(FormatErrorMessage(context.DisplayName))
End If
Return Nothing
End Function
End Class
看看这个线程的答案,
有一个名为MVC.ValidationToolkit的库。虽然我不确定它是否适用于日期时间字段。
可以在模型中使用 DateGreaterThanEqual 属性。 下面是我用来验证表单中的两个字段的代码片段。
[DataType(DataType.Date)]
[DisplayName("From Date")]
public DateTime? StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayName("To Date")]
[DateGreaterThanEqual("StartDate")]
public DateTime? EndDate { get; set; }