I have an entity called Doctor, in the create doctor form I added custom validation logic as follows:
public class UniqueDoctorNameAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string name = value.ToString();
HospitalEntities db = new HospitalEntities();
int count = db.Doctors.Where(d => d.DoctorName == name).ToList().Count;
if (count != 0)
return new ValidationResult("A doctor already exists with that name");
return ValidationResult.Success;
}
}
and then in the Doctor model class:
public class Doctor
{
[Required]
[Display(Name = "Name")]
[UniqueDoctorName]
public string DoctorName { get; set; }
}
and it works as expected when creating doctors but it also shows up in the edit form of Doctor, I know one way to remedy this is to use a viewmodel in the create form and do the validation there but that would require alot of debugging on my part as I've written alot of code depending on it being passed a Doctor model, so how do I fix that ?