Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom validation class - How to make universal
    primarykey
    data
    text
    <p>I am attempting to create a custom validation attribute for my MVC application. My code as written, works great for the properties specified in the code. I now want to expand it, so it is more general, because I have 5 other properties I would like to use this same attribute on.<br> The general idea is if the specified other property is true, then the property attached to the attribute must be > 0.</p> <p>I assume the way to do this is to create a constructor that accepts the value of the property and the value of the other property, but I can't seem to get it going. The specific problem I having is I can't find the correct way to pull in the needed values.</p> <p>Here is what I have:</p> <pre><code>public class MustBeGreaterIfTrueAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext context) { var model = context.ObjectInstance as HistoryViewModel; //ValidationResult result = null; // Validate to ensure the model is the correct one if (context.ObjectInstance.GetType().Name == null) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, "Context of type {0} is not supported. " + "Expected type HistoryViewModel", context.ObjectInstance.GetType().Name)); } // Here is the actual custom rule if (model.HistoryModel.IsRetired == true) { if (model.CounterA == 0) { return new ValidationResult("Please enter more information regarding your History"); } } else if ( model.HistoryModel.IsRetired == true ) { if ( model.ROCounter &gt; 0 ) return ValidationResult.Success; } // If all is ok, return successful. return ValidationResult.Success; } // Add the client side unobtrusive 'data-val' attributes //public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) //{ //} } </code></pre> <p>Thank you for you time.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload