none
question about validation attributes RRS feed

  • Question

  • I have been able to find MANY examples of validation attributes, but none that say what happens if the validation fails.  

    Should I expect to see the error message in the textbox of the class that is referenced, or should I expect an exception?

     [Range(10, 1000, 
            ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        public object Weight;
    

    (copied from an online example.)

    If I want it to throw an exception do I have to write custom attributes?

    thanks!

    Tuesday, November 21, 2017 12:57 AM

Answers

  • By themselves validation does nothing. You have to trigger the call. .NET ships with a Validator class that can do that. It is called by some frameworks automatically (WPF, MVC). When you use this class you can either get back the list of validation results that failed or have it throw a ValidationException with the results as the part of the exception.

    So, to validate with throw do this.

    Validator.ValidateObject(value, new ValidationContext(value), true);
    For an MVC app, the ModelState is automatically populated with validation errors before your controller action is run.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by danielsn Tuesday, November 21, 2017 3:01 PM
    Tuesday, November 21, 2017 2:51 PM
    Moderator

All replies

  • No, you don't throw exceptions on validation errors. You show the contents of ErrorMessage if it's not empty.string. You don't do any further processing, like saving data, until all validation pass, because ErrorMessage  = empty.string due to all validations pass.
    Tuesday, November 21, 2017 2:44 AM
  • By themselves validation does nothing. You have to trigger the call. .NET ships with a Validator class that can do that. It is called by some frameworks automatically (WPF, MVC). When you use this class you can either get back the list of validation results that failed or have it throw a ValidationException with the results as the part of the exception.

    So, to validate with throw do this.

    Validator.ValidateObject(value, new ValidationContext(value), true);
    For an MVC app, the ModelState is automatically populated with validation errors before your controller action is run.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by danielsn Tuesday, November 21, 2017 3:01 PM
    Tuesday, November 21, 2017 2:51 PM
    Moderator
  • Thanks Michael,

    Am eyeing using it in a device driver, so only choice is to throw exceptions.

    Tuesday, November 21, 2017 3:01 PM
  • Thanks Michael,

    Am eyeing using it in a device driver, so only choice is to throw exceptions.


    It's worthless and you have to write the validation logic yourself.
    Tuesday, November 21, 2017 4:03 PM