MVK 自定义注解

MVC Custom dataannotation

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

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; }
}

而习俗 class 是

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;
        }
    }
}

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

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

您的自定义 ValidationAttribute 类 只是检查是否有任何 users 具有相同的 usernameemail,其中包括当前 user,这会导致编辑场景中的验证失败。由于您试图防止 usernameemail 重复,因此实施需要注意正在保存的 userId

最简单的方法是通过 DbContext.ValidateEntity, since it looks like you are using Entity Framework. If you are not using Entity Framework, you can use ValidationContext in ValidationAttribute.IsValid in MVC. See http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx