我正在尝试使用EF6 Code First创建MVC ASP.NET应用程序。我正在学习如何为具有其他属性约束的属性添加自定义验证。
直接进入我的例子,我有一个名为TODL的类,它有2个属性。
using System;
using Avetmiss.Controllers;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Avetmiss.Models
{
public class TODL //Training organisation delivery location (NAT00020)
{
[StringLength(4, ErrorMessage = "postcode cannot be longer than 4 characters.")]
[Required]
public string postcode { get; set; }
[CustomValidation(typeof(CustomValidationManger),"country_id_validation")]
[Required]
public string country_id { get; set; }
}
}
现在我想在country_id上使用自定义验证:
如果邮编为“1”,则country_id不得为“1100”。
这是我的自定义验证,但它不起作用。
using Avetmiss.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Avetmiss.Controllers
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class CustomValidationManger : ValidationAttribute
{
public static ValidationResult country_id_validation(string country_id_value, TODL todl)//for TODL
{
if (todl.postcode.Equals("1") && country_id_value.Equals("1100"))
return new ValidationResult("country_id must not be 1100");
else
return ValidationResult.Success;
}
}
}