I find half the solutions everywhere, but I can’t get a real answer for this.
I created a validation attribute that inherits from ValidationAttribute and IClientValidatable.
Everything seems to be working fine, and if I put a check summary on the page, an error will appear.
however, I cannot get an error message next to the text box related to the property.
I think this is due to the fact that I need to add the name of the property to the check result.
HOWEVER, this is where it fails because I cannot get the member name from validationContext.
is there any way for this to happen? Or am I missing something?
public class AdmissionDayCaseAttribute : ValidationAttribute, IClientValidatable
{
private String DayCaseID;
private String AdmissionDateID;
private String DischargeDateID;
public AdmissionDayCaseAttribute(String DayCaseID, String AdmissionDateID, String DischargeDateID)
{
this.DayCaseID = DayCaseID;
this.AdmissionDateID = AdmissionDateID;
this.DischargeDateID = DischargeDateID;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
object AdmissionDate = GetPropertyValue(validationContext.ObjectInstance, AdmissionDateID);
object DischargeDate = GetPropertyValue(validationContext.ObjectInstance, DischargeDateID);
object AdmissionType = validationContext.MemberName == null ? null : GetPropertyValue(validationContext.ObjectInstance, validationContext.MemberName);
if (AdmissionDate != null && DischargeDate != null && AdmissionType != null)
{
if (AdmissionDate.Equals(DischargeDate) && DayCaseID.Equals(AdmissionType.ToString()))
{
return new ValidationResult(ErrorMessage, new List<String>() { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
private object GetPropertyValue(object instance,String propertyName)
{
Type itype = instance.GetType();
return itype.GetProperty(propertyName).GetValue(instance,null);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule vr = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
ValidationType = "admissiondaycase"
};
vr.ValidationParameters.Add(new KeyValuePair<string, object>("admissiondateid", AdmissionDateID));
vr.ValidationParameters.Add(new KeyValuePair<string, object>("dischargedateid", DischargeDateID));
vr.ValidationParameters.Add(new KeyValuePair<string, object>("daycaseid", DayCaseID));
yield return vr;
}
EDIT / UPDATE
the view is as follows:
<tr>
<td>
@Html.LabelFor(x => x.AdmissionTypeID)
</td>
<td>
@Html.CustomDropDownListFor(a => a.AdmissionTypeID, Lookup.AdmissionTypes,Default.Constant.DROPDOWN)
@Html.ValidationMessageFor(a=>a.AdmissionTypeID)
</td>
</tr>
javascript -, , , -
,