1

I am having a difficult finding out how to do a conditional required validation.

Basically I have an dialog object that needs to be validated. It has a bool which determines a certain state of the dialog.

If that state is true then a property needs to be validated, if it is false then the property is not used and thus needs no validation. At the same time I would like to retain the standard validation behavior when a value is not valid, namely the red border around the control that the property is bound to.

Example code on what I got:

public class Dialog
{
    public bool UseValidation { get; set; }

    [Required]
    [StringLength(15)]
    public string NotNullString { get; set; }
}

The reason for this is that I want to validate the dialog when the OK button is pressed, thus using the Validator.TryValidateObject() method.

Perry
  • 2,250
  • 2
  • 19
  • 24

1 Answers1

1

If you are using DataBinding, you can create explicit getters and setters for your property, and throw an exception if the data is not valid in the setter. You can then set the ValidatesOnException property of the textbox binding to True.

public string NotNullString { 
   get { return _NotNullString; }
   set { 
          if(UseValidation && (String.IsNullOrEmpty(value) || value.Length > 15)) {
              throw new Exception("Value must be between 1 and 15 characters long.");
          }
          _NotNullString = value;
       }
}

Here is a good article: http://www.codeproject.com/Articles/86955/Silverlight-4-Data-Validation-Tip-of-the-Day-Part

Misha
  • 571
  • 5
  • 17
  • But how would I validate that when the setter has never been called? I need validation to be done on demand through the Validator.TryValidateObject() method. I should probably edit that in my question – Perry Jul 08 '12 at 02:33
  • 1
    Is this what you are looking for? http://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject – Misha Jul 08 '12 at 02:56