User212939177 posted
Hello.
I have a custom validation attribute which aims to compare the values of two other properties in a class in order to assess the validity of a another property. As an example, I have a text box for the name of a department, but a user can also click a checkbox
to say it's the same department as the one they work in and can also select a department from a list. The text box is intended for when the user wishes to add a new department for the purposes of what they're entering.
For this to work I need validation which indicates that the DepartmentName(the text box) field is Required when SameDepartment(the checkbox) and DepartmentID(the combo) are both null. Here is the code for the validation attribute I've developed:
public class ValidationAttributes
{
public class RequiredIfTwo : RequiredAttribute
{
private String Property1Name { get; set; }
private Object Desired1Value { get; set; }
private String Property2Name { get; set; }
private Object Desired2Value { get; set; }
public RequiredIfTwo(String property1Name, Object desired1value, String property2Name, Object desired2value)
{
Property1Name = property1Name;
Desired1Value = desired1value;
Property2Name = property2Name;
Desired2Value = desired2value;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object property1value = type.GetProperty(Property1Name).GetValue(instance, null);
Object property2value = type.GetProperty(Property2Name).GetValue(instance, null);
if (property1value == Desired1Value && property2value == Desired2Value)
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}
}
Here's how it's used in the viewmodel:
[RequiredIfTwo("PlacementDepartmentName", null, "SameDepartment", false,
ErrorMessage = "A host department needs to be selected or added")]
public int? PlacementDepartmentId { get; set; }
[RequiredIfTwo("PlacementDepartmentId", null, "SameDepartment", false,
ErrorMessage = "Host department's name needs to be added when creating a department")]
public string PlacementDepartmentName { get; set; }
public bool SameDepartment { get; set; }
When I run the page and don't enter anything in any of the three fields the validation is still returning a success. I've run it in debug and can see that the values meet the requirements, here is the output from the immediate window when I query various
parts of the If statement:
? property1value == Desired1Value && property2value == Desired2Value
false
-- overall statement not returning true
? property1value == Desired1Value
true
-- first part is working ok
? property2value == Desired2Value
false
-- second part not
? property2value
false
? Desired2Value
false
-- But both values are showing as false so why is the comparison not returning true?