I build a custom attribute the other day to validate whether the field is filled with a value when a specific enum item is selected.
I wrote the class and functions and the validator methods are hit both on server and client side, but for whatever reason there is no error message despite form.valid() returning false.
I can't for the love of god figure out what I am doing wrong.
Model
[RequiredIf("AntragStatus", new object[] { AntragStatus.UnterlagenAngefordert })]
public string Bearbeiter { get; set; }
Validator
public class RequiredIf : ValidationAttribute, IClientValidatable
{
private string _dependentProperty { get; set; }
private object[] _targetValues { get; set; }
public RequiredIf(string dependentProperty, object[] targetValues)
{
_dependentProperty = dependentProperty;
_targetValues = targetValues;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
var fieldValue = field.GetValue(validationContext.ObjectInstance, null);
var fieldValueEqualsTargetValue = false;
foreach (var targetValue in _targetValues)
{
if (fieldValue.Equals(targetValue))
{
fieldValueEqualsTargetValue = true;
if (value != null)
{
return ValidationResult.Success;
}
}
}
return fieldValueEqualsTargetValue ? new ValidationResult("Es sind nicht alle benötigten Felder gefüllt!") : ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif"
};
rule.ValidationParameters.Add("dependentproperty", _dependentProperty);
rule.ValidationParameters.Add("targetvalues", GetTargetValues());
yield return rule;
}
private string GetTargetValues()
{
var tValues = "";
foreach (var targetValue in _targetValues)
{
tValues += targetValue + ",";
}
tValues = tValues.Remove(tValues.Length - 1);
return tValues;
}
}
JavaScript
$.validator.addMethod("requiredif",
function (value, element, parameters) {
var isInTargetValues = false;
var id = parameters["dependentproperty"];
var targetValues = parameters["targetvalues"].split(",");
var controls = ASPxClientControl.GetControlCollection();
var statusValue = controls.GetByName(id).GetValue();
for (var i = 0; i < targetValues.length; i++) {
if (targetValues[i] == statusValue) {
isInTargetValues = true;
if ($.trim(value) != "") {
return true;
}
}
}
if (!isInTargetValues) {
return true;
} else {
return false;
}
});
$.validator.unobtrusive.adapters.add(
"requiredif",
["dependentproperty", "targetvalues"],
function (options) {
options.rules["requiredif"] = {
dependentproperty: options.params["dependentproperty"],
targetvalues: options.params["targetvalues"]
};
var msg = "Das Feld " + options.element.name + " muss gefüllt sein";
options.messages["requiredif"] = msg;
});
Web.Config
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>
Razor
@{
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
}