In this post I’m again comparing two features of Silverlight and Flex, this time we’re going to take a look at how data validation is implemented on both platforms. This will be a very interesting comparison, since Flex and Silverlight take entirely different approaches. Which one is better? I can let you know in advance that one of the two is a bit broken. Read on to find out which one……
Flex Data Validation
Let’s take a look a the following code:
and the following class:
I’m going to explain data validation in Flex as simple as possible. The first code snippet is the user interface part. You can see that this is a very simple user interface with just a TextBox in which a user can enter an age. The entered age is passed on to an instance of the Person class shown in the second code snippet. This is done by using the new two way databinding feature in Flex 4, which uses the “@” in front of the databinding expression. At startup the creationComplete event is used to initialize the Person with an age of 20:
When the user enters an invalid (negative, decimal or not a number) value the user interface changes to this:
This all happens automatically because of the NumberValidator used on line 22. Data validation in Flex is done using the Validator class and it’s different sub classes like NumberValidator. You just configure a validator with a couple of things:
- source: This is the object which holds the property you want to validate.
- property: This is the property you want to validate.
- Validator specific properties: These include error messages of the different validations a validator can do, or for example a regex when using a RegExpValidator.
- trigger: This is the object which dispatches the event that triggers validation. I don’t set this in the code above, because by default this is the same object as the source property.
- triggerEvent: The event that triggers the validation, by default this is the valueCommit event. Since the source in the example above is the TextBox and the valueCommit event is used, validation is triggered when the user presses enter or the TextBox loses focus.
There are a couple of things I really like about Flex’ approach. Firstly, these are the built in validators:
And if those are not enough, you can create your own validator by inheriting from the Validator class and override the doValidation() method. The second thing I like is that you can easily customize the triggering of the validation:
By setting the triggerEvent to “change”, validation is now triggered with every button the user presses instead of when losing focus or pressing enter. There are also things that I don’t like, for example, data validation doesn’t prevent databinding. This means that even when an incorrect value is set in the TextBox, the value is still propagated to the setter of the Person class. If I did a check in the setter and threw an exception, I would have a serious problem because there is no easy place to catch the exception, except for the global error handler. Next to that, certain exceptions are swallowed by the databinding engine and others are not. Lastly, Flex’ Validator classes don’t play nice with asynchronous data validation.
Silverlight Data Validation
I’ve built the same user interface as in the Flex example. This time, three code snippets because of the code behind model Silverlight uses. First up, the XAML:
Next up, the code behind:
Lastly, the Person class:
When you start the application it looks like:
And when you enter an invalid value:
Silverlight takes a whole different approach to data validation, in Flex validation is the responsibility of the Validator objects, in Silverlight the validation is the responsibility of the domain object to which is data bound. Of course, within this object you can delegate the responsibility as much as you like. As of Silverlight 4, we have three ways of doing data validation:
- By throwing exceptions in the setters of the property of the data bound object. The message in the exception becomes the validation error message.
- By implementing the IDataErrorInfo interface, this interface defines two members:
- An indexer, which is called by the binding engine supplying a property name, if the property with the supplied name is valid, you can return null otherwise the validation error message.
- An Error property which isn’t used by the binding engine but you can use to get a single error message for the entire object.
- By implementing the INotifyDataError interface. This interface is like the IDataErrorInfo interface, but has supports for events. With the IDataError interface the Indexer is called every time the value of the property changes through databinding. With the INotifyDataError interface, the bound object is examined for validation errors whenever you fire a specific event. This means that you can contact a server to do the validation and when you receive the response, you can fire the event. In short, INotifyDataError provides support for asynchronous data validation.
You have the specify which of the above options you want to use in the binding expression. When you take a look at line 12 in the first code snippet, you can see that I use two of above features, namely the IDataError interface and the exceptions option. If I wanted to use the INotifyDataError interface, I should have supplied the “ValidatesOnNotifyDataErrors = True” option in the binding expression. Take a look at the Person class, you can see that it implements the IDataError interface, but doesn’t throw any exceptions in a setter. So why the ValidatesOnExceptions option in the binding expression? I’ll come back to that later :).
So how does the IDataErrorInfo interface work? Every time the binding engine updates the property value, it calls the indexer on line 29 of the last code snippet afterwards, supplying the name of the property it has just updated. I’ve implemented the indexer on line 29 as if I had multiple properties. When you return a string, it’s a sign to the binding engine that a validation error has occurred and the returned string becomes the error message. When the binding engine get’s a sign that a validation error has occurred, it transitions the bound control, in this case the TextBox to the “InvalidFocusedState” or the “InvalidUnFocused” state. So the control template of a control determines how a control looks when a data validation error occurs. If you want to adjust this look, you have to retemplate the control and define your own look for the invalid states.
There are a couple of things I like about Silverlight’s data validation model. The first is that there is support for asynchronous data validation. The second thing is that this data validation model works really well in a MVVM environment, with the View having all the knowledge it needs to change itself when a data validation error occurs. If you want to customize it, just retemplate the view, while in Flex you have to write some actionscript code. The difficult thing is, where are you going to put this code in a MVVM scenario?
So for me (because I really like MVVM and asynchronous data validation) Silverlight would have been the winner. I deliberately say “would have been”, because I’m going to make a bold statement here…I think that Silverlight’s data validation system is a bit broken… There I’ve said it… but before the flaming begins, let me elaborate.
Silverlight’s broken validation system
I said that I would come back to the “ValidatesOnExceptions” option in the binding expression on line 12 in the first code snippet. The reason i have it there is that this is the only way I can get a notification when a user enters a string that can’t be converted to an integer. It turns out that Silverlight’s binding system does some pre-validation before it supplies the value to the bound object, if this validation fails, the value never reaches the bound object. This happens when I enter a string that can’t be converted to a number:
It’s somewhat logical that the binding engine does some pre-conversion. The problem is, that the message shown can’t be customized! I’ve tried a couple of possible solutions:
- Create my own IValueConverter which does the string to integer conversion and supply my own message. The problem with this approach is that exceptions in the IValueConverter don’t trigger Silverlight’s validation system, only exceptions in property setters can do that. This means that the IValueConverter can’t let the system know that validation fails. How can this be you ask? Clearly the default converter triggers the validation system? This is because the default converter throws a ValidationException, this exception get’s recognized by the binding engine and gets a special treatment so that it triggers validation. But if you want to throw this exception from your own IValueConverter, you’re in for a surprise because the constructor is internal, which essentially means that only Microsoft code can throw this exception.
- Catch the FocusLost event of the TextBox, manually set the error messages of the control and manually transition the control to an InValid state using the VisualStateManager. While you can manually transition a control to an InValid state, you can’t set a controls error messages. This “Errors” property which contains the messages for a control is an attached property from the Validation class. You guessed it…the required setter to manually set the error messages is internal.
Another example of the problem: what if an user could enter an address in a TextField in a specified format (street and number) and the bound business object expected an Address object. I would use an IValueConverter to do the conversion from string to Address, which is the whole purpose of value converters. But the converter could never ever let the user know that he / she entered the address in a wrong format. This is why the validation mechanism in Silverlight is broken and if you want to fix it, you have to resort to a whole custom solution and can’t make use of the built in InValid states all the Silverlight controls have, because you can’t specify the error message to show. This means that you have to do everything yourself for all the pre-validation that the binding engine does, if the error message doesn’t suit your needs. What can Microsoft do to fix this? Very simple:
- Make the constructor of the ValidationException public.
- Or let all exceptions in an IValueConverter trigger the validation system.
- Make the attached property setters in the Validation class public, so that when you resort to a whole custom solution, you can still make use of the built in InvalidStates.
Phew, This post has become a little longer than I first suspected. When I develop a Flex application, I notice that having these built in validators really speed up the development. When I develop a Silverlight application, I notice that trying to work around the quirks in the validation system slows me down to a point that I choose a whole custom solution. Don’t get me wrong, I really think that Silverlight’s validation system is on the right track: it integrates beautifully with the MVVM pattern and has support for asynchronous validation. But the issues outlined above need to be fixed. When they are fixed, I think Silverlight’s validation system could surpass Flex’ validation system, certainly in MVVM scenario’s. But for now, Flex’ data validation system is more useful to me.