问题
i create two custom dataannotation for this class as follow
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; }
}
and the custom class is
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;
}
}
}
and other is
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;
}
}
}
this annotation worked well when i create new user,
but the problem is when i update users and didn't update username or email my custom annotation Executed, then i gives me error because username and email already exist in database.
回答1:
Your custom ValidationAttribute
classes are simply checking if any users
have the same username
or email
, which includes the current user
, which causes validation to fail in the edit scenario. Since you are attempting to prevent duplicate username
and email
, the implementation needs to be aware of the Id
of the user
it is saving.
The simplest way to do this is via 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
来源:https://stackoverflow.com/questions/32804112/mvc-custom-dataannotation