This question is locked. New answers and comments are not allowed.
Hi there.
I have a ViewModel class where I need to validate one property based on the value of another.
I've found a solution using a Custom Validator for the class like this:
| [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] |
| public sealed class ValidateValueForFormat: ValidationAttribute |
| { |
| private const string _defaultErrorMessage = "bleh bleh bleh"; |
| private readonly object _typeId = new object(); |
| public ValidateValueForFormat(string formatProp, string valueProp) |
| : base(_defaultErrorMessage) |
| { |
| FormatProp = formatProp; |
| ValueProp = valueProp; |
| } |
| public string FormatProp |
| { |
| get; |
| private set; |
| } |
| public string ValueProp |
| { |
| get; |
| private set; |
| } |
| public override object TypeId |
| { |
| get |
| { |
| return _typeId; |
| } |
| } |
| public override string FormatErrorMessage(string name) |
| { |
| return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString); |
| } |
| public override bool IsValid(object value) |
| { |
| bool result = true; |
| PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); |
| int format = |
| (int)properties.Find(FormatProp, true /* ignoreCase */).GetValue(value); |
| string value = properties.Find(Valor, true /* ignoreCase */).GetValue(value); |
| ....... |
| here I check the value against the format and set "result" to true |
| if ok or false if not ok... |
| ....... |
| return result; |
| } |
| } |
Then I place my validation in the ViewModel's class header like this :
| [ValidateValueForFormat("Format","Value",ErrorMessage="The value doesn't fit the format needed."] |
| public class MyViewModel |
| { |
| public int Format { get; set; } |
| public string Value {get; set; } |
| } |
I bind a list of this class' objects to an ajax grid, and make it editable. When I edit the field "value" and click on update, the validation class gets called, the isvalid method returns false, the formaterrorstring method is also called, but don't matter the result, valid or invalid, the Update always gets successful and my property gets a value that wasn't supposed to get.
Does your grid support this kind of validations? I find weird that the validation actually gets called but the grid ignores the result...
Thanks!!