I have some validation meta data on my model:
[RequiredIf("IsNewCustomer", true, ErrorMessage="Tax ID is missing")]
public string TaxIDNumber { get; set; }
I also have the standard LabelHelper code to put asterisks next to any required field.
if (displayOptions == DisplayOptions.ShowRequired && metadata.IsRequired )
{
//... add span html
}
If the metadata tag is [Required] this code works fine. However if I use RequiredIf or RequiredIfTrue, the isRequired property is always set to false. The validation still works, on submit however. The modelstate is invalid and the error message is displayed.
I have tried to create a custom override to the DataAnnotationsModelMetadataProvider:
protected override ModelMetadata CreateMetadata(System.Collections.Generic.IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var _default = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
_default.IsRequired = attributes.Where(x => x is RequiredAttribute).Count() > 0;
return _default;
}
However none of this code runs until the validation piece is called, so the metadata is not updated until the form attempts to post.
Any ideas how to update the metadata on dynamic required tags as the page loads so my required field indicators still work?