Validation before property set

Validation before property set

Old forum URL: forums.lhotka.net/forums/t/3684.aspx


bgilbert posted on Wednesday, October 10, 2007

I have a numeric property (integer). When a user enters a value, I want to validate that it is numeric. However, it will never make it to any validation rule because it will throw an exception when trying to pass the value to the property set. I've worked around this by putting validation in my UI textbox's Validating event. Obviously, I'd rather maintain all rules in my business object and I'd rather not use exception handling to trap this.

Is there any way for validation rules to intercede between databinding and property set methods?

ajj3085 replied on Wednesday, October 10, 2007

I think to work around this you'll have to store the value as a string, and then have a validation rule which uses int.TryParse.  Otherwise, if you store and expose the property as an integer, you'll just need to make the UI disallow non-numeric characters.  Some controls handle this, such as NumericTextBox from Infragistics; its only purpose is to store numbers (and some related things, like $ or %) but the value it pushes is a plain number.

I'm conflicted as to whether or not this is a true business rule; if your type says it must be an int, it has to be an int, so you don't have a choice except to disallow alphas.  I think Rocky posted on this topic before, but I don't recall for sure.

bgilbert replied on Wednesday, October 10, 2007

ajj3085:
I think to work around this you'll have to store the value as a string, and then have a validation rule which uses int.TryParse.  Otherwise, if you store and expose the property as an integer, you'll just need to make the UI disallow non-numeric characters.  Some controls handle this, such as NumericTextBox from Infragistics; its only purpose is to store numbers (and some related things, like $ or %) but the value it pushes is a plain number.

I'm conflicted as to whether or not this is a true business rule; if your type says it must be an int, it has to be an int, so you don't have a choice except to disallow alphas.  I think Rocky posted on this topic before, but I don't recall for sure.


I tend to agree. If this were a date field, I would use a datetime type control.

Thanks for the feedback.

Copyright (c) Marimer LLC