Bạn có thể sử dụng thuộc tính xác thực tùy chỉnh ở đây là ví dụ của tôi có ngày tháng. Nhưng bạn có thể sử dụng nó với ints quá.
Thứ nhất, đây là mô hình:
public DateTime Beggining { get; set; }
[IsDateAfterAttribute("Beggining", true, ErrorMessageResourceType = typeof(LocalizationHelper), ErrorMessageResourceName = "PeriodErrorMessage")]
public DateTime End { get; set; }
Và đây là thuộc tính riêng của mình:
public sealed class IsDateAfterAttribute : ValidationAttribute, IClientValidatable
{
private readonly string testedPropertyName;
private readonly bool allowEqualDates;
public IsDateAfterAttribute(string testedPropertyName, bool allowEqualDates = false)
{
this.testedPropertyName = testedPropertyName;
this.allowEqualDates = allowEqualDates;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
if (propertyTestedInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
}
var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
if (value == null || !(value is DateTime))
{
return ValidationResult.Success;
}
if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
{
return ValidationResult.Success;
}
// Compare values
if ((DateTime)value >= (DateTime)propertyTestedValue)
{
if (this.allowEqualDates && value == propertyTestedValue)
{
return ValidationResult.Success;
}
else if ((DateTime)value > (DateTime)propertyTestedValue)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessageString,
ValidationType = "isdateafter"
};
rule.ValidationParameters["propertytested"] = this.testedPropertyName;
rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
yield return rule;
}
Bạn cần phải hoàn thành ví dụ này với xác nhận client-side: 'jQuery.validator.addMethod ('isdateafter', function (giá trị, yếu tố, params) { nếu (!/Không hợp lệ | NaN/.test (ngày mới (giá trị))) { trả về ngày (giá trị) mới> Ngày mới(); } lợi nhuận làNaN (giá trị) && isNaN ($ (params) .val()) || (parseFloat (giá trị)> parseFloat ($ (params) .val())); }, ''); jQuery.validator.unobtrusive.adapters.add ('isdateafter', {}, chức năng (tùy chọn) { options.rules ['isdateafter'] = true; options.messages ['isdateafter'] = options.message; }); ' – LoBo
Dường như có lỗi do dòng' if (this.allowEqualDates && value == propertyTestedValue) '. Điều này làm việc: 'if (this.allowEqualDates && value.Equals (propertyTestedValue))' hoặc thậm chí 'if (this.allowEqualDates && (DateTime) value == (DateTime) propertyTestedValue)'. – publicgk