MVC自定义数据注释

时间:2015-09-27 02:55:37

标签: c# asp.net-mvc data-annotations

我为这个类创建了两个自定义数据注释,如下所示

public class users
{
    public int Id { set; get; }
    [Required(ErrorMessage = "username is Required")]
    [usernameValidation(ErrorMessage= "Sorry this name is already exist")]
     // [MaxLength(ma)]
    public string username { set; get; }

    [Required(ErrorMessage = "Password is required")]
    [DataType(DataType.Password)]
    public string password { set; get; }

    [Required(ErrorMessage = "Confirm Password is required")]
    [StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
    [DataType(DataType.Password)]
    [Compare("password")]
    public string confirmPassword { set; get; }

    [Required(ErrorMessage = "email is required")]
    [DataType(DataType.EmailAddress)]
    [emailValidation(ErrorMessage = "Sorry this e-mail is already exist")]
    public string email { set; get; }

    [Required]
    public int type { set; get; }

    public string photopath { set; get; }

    [DataType(DataType.MultilineText)]
    public string address { set; get; }

    [DataType(DataType.MultilineText)]
    public string note { set; get; }
}

,自定义类是

public class emailValidation : ValidationAttribute
{
    db_context db = new db_context();
    public override bool IsValid(object value)
    {
        int query = (from res in db.users
                     where res.email == value.ToString() 
                     select res).Count();
        if (query == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

和其他是

public class usernameValidation : ValidationAttribute
{
    db_context db = new db_context();
    public override bool IsValid(object value)
    {
        int query = (from res in db.users
                     where res.username == value.ToString() 
                     select res).Count();
        if (query == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

当我创建新用户时,这个注释效果很好,

但问题是当我更新用户并且没有更新用户名或通过电子邮件发送我的自定义注释时执行,然后我给了我错误,因为用户名和电子邮件已存在于数据库中。

1 个答案:

答案 0 :(得分:0)

您的自定义ValidationAttribute课程只是检查是否有usersusernameemail,其中包含当前的user,这会导致验证在编辑方案中失败。由于您试图阻止重复usernameemail,因此实施需要了解它正在保存的Id {。}}。

最简单的方法是通过DbContext.ValidateEntity,因为它看起来像是在使用Entity Framework。如果您没有使用Entity Framework,则可以在MVC中的user中使用ValidationContext。见http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx