model-view-controller – 比较Dates DataAnnotations验证asp.net mvc
|
假设我有一个StartDate和一个EndDate,我想检查EndDate是否距离开始日期不超过3个月 public class DateCompare : ValidationAttribute
{
public String StartDate { get; set; }
public String EndDate { get; set; }
//Constructor to take in the property names that are supposed to be checked
public DateCompare(String startDate,String endDate)
{
StartDate = startDate;
EndDate = endDate;
}
public override bool IsValid(object value)
{
var str = value.ToString();
if (string.IsNullOrEmpty(str))
return true;
DateTime theEndDate = DateTime.ParseExact(EndDate,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
DateTime theStartDate = DateTime.ParseExact(StartDate,CultureInfo.InvariantCulture).AddMonths(3);
return (DateTime.Compare(theStartDate,theEndDate) > 0);
}
}
我想将此实现到我的验证中
我知道我在这里得到了一个错误……但我怎样才能在asp.net mvc中进行这种业务规则验证 解决方法这是一个迟到的答案,但我想分享给其他人.这是我如何做到这一点,以便使用不显眼的客户端验证验证所有内容:>创建属性类: public class DateCompareValidationAttribute : ValidationAttribute,IClientValidatable
{
public enum CompareType
{
GreatherThen,GreatherThenOrEqualTo,EqualTo,LessThenOrEqualTo,LessThen
}
private CompareType _compareType;
private DateTime _fromDate;
private DateTime _toDate;
private string _propertyNameToCompare;
public DateCompareValidationAttribute(CompareType compareType,string message,string compareWith = "")
{
_compareType = compareType;
_propertyNameToCompare = compareWith;
ErrorMessage = message;
}
#region IClientValidatable Members
/// <summary>
/// Generates client validation rules
/// </summary>
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context)
{
ValidateAndGetCompareToProperty(metadata.ContainerType);
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessage;
rule.ValidationParameters.Add("comparetodate",_propertyNameToCompare);
rule.ValidationParameters.Add("comparetype",_compareType);
rule.ValidationType = "compare";
yield return rule;
}
#endregion
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
// Have to override IsValid method. If you have any logic for server site validation,put it here.
return ValidationResult.Success;
}
/// <summary>
/// verifies that the compare-to property exists and of the right types and returnes this property
/// </summary>
/// <param name="containerType">Type of the container object</param>
/// <returns></returns>
private PropertyInfo ValidateAndGetCompareToProperty(Type containerType)
{
var compareToProperty = containerType.GetProperty(_propertyNameToCompare);
if (compareToProperty == null)
{
string msg = string.Format("Invalid design time usage of {0}. Property {1} is not found in the {2}",this.GetType().FullName,_propertyNameToCompare,containerType.FullName);
throw new ArgumentException(msg);
}
if (compareToProperty.PropertyType != typeof(DateTime) && compareToProperty.PropertyType != typeof(DateTime?))
{
string msg = string.Format("Invalid design time usage of {0}. The type of property {1} of the {2} is not DateType",containerType.FullName);
throw new ArgumentException(msg);
}
return compareToProperty;
}
}
注意:如果要验证时间长度,请向约束器添加另一个参数,并更改此特定类型的比较的枚举数
$.validator.addMethod("compare",function (value,element,parameters) {
// value is the actuall value entered
// element is the field itself,that contain the the value (in case the value is not enough)
var errMsg = "";
// validate parameters to make sure everyting the usage is right
if (parameters.comparetodate == undefined) {
errMsg = "Compare validation cannot be executed: comparetodate parameter not found";
alert(errMsg);
return false;
}
if (parameters.comparetype == undefined) {
errMsg = "Compare validation cannot be executed: comparetype parameter not found";
alert(errMsg);
return false;
}
var compareToDateElement = $('#' + parameters.comparetodate).get();
if (compareToDateElement.length == 0) {
errMsg = "Compare validation cannot be executed: Element to compare " + parameters.comparetodate + " not found";
alert(errMsg);
return false;
}
if (compareToDateElement.length > 1) {
errMsg = "Compare validation cannot be executed: more then one Element to compare with id " + parameters.comparetodate + " found";
alert(errMsg);
return false;
}
//debugger;
if (value && !isNaN(Date.parse(value))) {
//validate only the value contains a valid date. For invalid dates and blanks non-custom validation should be used
//get date to compare
var compareToDateValue = $('#' + parameters.comparetodate).val();
if (compareToDateValue && !isNaN(Date.parse(compareToDateValue))) {
//if date to compare is not a valid date,don't validate this
switch (parameters.comparetype) {
case 'GreatherThen':
return new Date(value) > new Date(compareToDateValue);
case 'GreatherThenOrEqualTo':
return new Date(value) >= new Date(compareToDateValue);
case 'EqualTo':
return new Date(value) == new Date(compareToDateValue);
case 'LessThenOrEqualTo':
return new Date(value) <= new Date(compareToDateValue);
case 'LessThen':
return new Date(value) < new Date(compareToDateValue);
default:
{
errMsg = "Compare validation cannot be executed: '" + parameters.comparetype + "' is invalid for comparetype parameter";
alert(errMsg);
return false;
}
}
return true;
}
else
return true;
}
else
return true;
});
这只关注客户端不显眼的验证.如果你需要服务器端,你必须在isValid方法的覆盖中有一些逻辑.此外,您可以使用Reflection使用显示属性等生成错误消息,并使消息参数可选. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – ASP.NET MVC – 如何获取一个动作的完整路径
- asp.net-mvc – MVC 4 Ajax.beginform提交 – 导致完全回发
- asp.net-mvc-3 – 分页/排序不适用于部分视图中使用的网格
- asp.net-mvc – 如何进入MVC4源代码,而无需构建程序集
- asp.net-core – 如何使用ASP.NET Core中的JWT授权重定向到
- asp.net – 如何自动执行功能/集成测试和数据库回滚
- asp.net-mvc-3 – 不支持使用相同的DbCompiledModel来针对不
- asp.net-mvc – 在ASP.NEt MVC 3中传递Html.BeginForm()中D
- asp.net-mvc – EditorFor()和additionalViewData:如何在h
- asp.net-core – asp.net核心依赖注入问题 – AddScoped没有
- asp.net – 实体框架4 – 从模型更新数据库模式
- asp.net-mvc-2 – 如何设置RadioButtonFor()在AS
- asp.net – 即使在IIS的web.config中使用标签后,
- ASP.NET从.aspx链接返回图片
- ASP.NET Web API返回可查询的DTO?
- asp.net – ClientScriptManager.GetPostBackEve
- asp.net-mvc – AntiForgeryToken登录后无效
- asp.net-mvc – Visual Studio总是能够在源代码视
- ASP.NET URL重写
- asp.net – MSBuild:自动收集db迁移脚本?
