Thursday, June 19, 2008

Quick Silverlight tip: How to set format and validate value in TextBox?

Today morning I got an email from one of Microsofties, asking following question:

Is there any way to set format and validation on TextBox in Silverlight 2. TextBox format: Date Format, Currency Format etc, TextBox validation: Regular date expression, should allow only numeric etc. If it’s possible out-of-box how do I do it?

The answer is, that there is no data validation or formatting in Silverlight, however it’s very simple to build converter to format binded value. Here the code of the converter:

public class TextFormatConverter:IValueConverter
   {

       #region IValueConverter Members

       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           return Format(value, parameter);
       }
       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           return Format(value, parameter);
       }

       object Format(object value, object param)
       {
           if (value == null)
               return value;
           int ri;
           double rd;
           if (int.TryParse(value.ToString(), out ri))
           {
               return string.Format(param.ToString(), ri);
           }
           else if (double.TryParse(value.ToString(), out rd))
           {
               return string.Format(param.ToString(), rd);
           }
           else
           {
               return string.Format(param.ToString(), value);
           }
       }

       #endregion
   }

Here the usage:

<TextBox Text="{Binding String, Source={StaticResource data}, Mode=TwoWay, Converter={StaticResource formatConverter}, ConverterParameter='{0:0.00}'}" />

Regarding validators – There is no ValidationRule or IDataErrorInfo in Silverlight right now. If you want to have it, you’ll need to write your own custom TextBox with validation. But, I’ll speak next time about it. ValidatingTextBox with format support will be a part of Silverlight controls library when I’ll have a time for it.

Have a nice day and be good people.

No comments: