I am just getting into custom attributes, and I absolutely love them. I am wondering if it is possible to create an attribute that gets applied to a property and denotes the name of another property in the same object. If would check to see if the referenced property has a value, and if so, the decorated attribute would be required. Something like this:
[RequiredIfNotNull("ApprovedDate")]
[DisplayName("Approved By")]
[StringLength(50, ErrorMessage = "{0} must not exceed {1} characters")]
public string ApprovedBy { get; set; }
[DisplayName("Approved Date")]
[DisplayFormat(DataFormatString = "{0:d}")]
[PropertyMetadata(ColumnName = "ApprovedDate")]
public DateTime? ApprovedDate { get; set; }
So the approved by property is decorated with the RequiredIfNotNull attribute which references the property to check for null. In this case, the Approved Date. I would want the ApprovedBy Property to be required if the ApprovedDate had a value. Is it possible to do something like this? If so can you implement it server side and client side?
Here is what I came up with: Server side:
Client side:
I set this up to accept a model or prefix value and then the name of the actual field. The reason for this is that in many cases, I will add an object as part of a model, and that will cause the form id for that element to be rendered as ModelName_FieldName. But it also occurred to me that you may or may not use a model with an embedded object. In that case the id would just be FieldName, so the clientside code checks to see if the element exists by FieldName, and if not it returns ModelName_FieldName otherwise it just returns the FieldName. I didn't do it yet, but I should probably check to make sure the resulting fieldname has is not null.
and then to decorate your property you would do something like this:
my model looks like this:
my view implementation looks like this:
So my client side element has the following ID: