Data Validation in Windows Phone 8

Aug 15, 2013 at 2:10 PM
Edited Aug 15, 2013 at 2:25 PM
Hi,

I wanted to know how can I create custom data validation rules in Windows Phone 8.

I found this to be particularly easy in WPF where I just bind my custom validation rules by simply calling the various validation rule classes which override the Validate method which has my validation logic mentioned inside the overridden Validate method.

This is the example code that I wrote in WPF in order to accomplish this:

I mentioned the name space where all my validation classes are located in my Project in the window or page which contains the TextBox control which I need to validate as below:
xmlns:validations="clr-namespace:InterestRateCalculator.Validations"
I have stored all of my validation classes inside a folder called Validations in the root of my project.

Now, for example, if I need to validate the TexBox where the user needs to enter the deposit / principle amount, I need to ensure that the user ONLY enters numbers and numbers ranging between 100 and 100000000. In order to check this clause, I bind the Text Property of the TextBox as below:
<TextBox Name="depositAmountTextBox" VerticalAlignment="Center" Width="100" Style="{StaticResource textStyleTextBox}" Validation.ErrorTemplate="{StaticResource validationTemplate}">
                        <TextBox.Text>
                            <Binding RelativeSource="{RelativeSource Self}" Path="Text">
                                <Binding.ValidationRules>
                                    <validations:DepositAmountValidation />
                                </Binding.ValidationRules>
                            </Binding>
                        </TextBox.Text>
</TextBox>
Inside the DepositAmountValidation class inside the Validations folder, I have the following logic:
class DepositAmountValidation : ValidationRule
    {
        string depositAmountPattern = @"[^0-9]";
        double depositAmount;

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if ((string)value != "")
            {
                if (Regex.IsMatch((string)value, depositAmountPattern))
                {
                    return new ValidationResult(false, "Deposit Amount should only contain numbers and nothing else.");
                }
                else
                {
                    depositAmount = Convert.ToDouble(value);
                    if (depositAmount < 100 || depositAmount > 100000000)
                    {
                        if (depositAmount < 100)
                        {
                            return new ValidationResult(false, "Deposit Amount should be a minimum of 100.");
                        }
                        else if (depositAmount > 100000000)
                        {
                            return new ValidationResult(false, "Deposit Amount CANNOT EXCEED 10 CRORES.");
                        }
                        else
                        {
                            return ValidationResult.ValidResult;
                        }
                    }
                    else
                    {
                        return ValidationResult.ValidResult;
                    }
                }
            }
            else
            {
                return new ValidationResult(false, "Deposit Amount is Required.");
            }
        }
    }
The above code, first checks and makes sure that the user has not left the Deposit Amount TextBox empty and also ensures that they have only entered numbers and numbers ranging between 100 and 100000000. If any of these conditions haven't been met, then a false validation with a suitable message is returned for the user to read, otherwise, the validation will pass and proceed.

The ValidationTemplate and the TextBox styles are stored in the App.xaml page as application resources as below:
<Application.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textStyleTextBox" TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Background" Value="Yellow"/>
                </Trigger>
            </Style.Triggers>
        </Style>
</Application.Resources>
So, when the user does not enter a valid entry in any of the test boxes which are being validated, then it will look something like this:

Image

https://skydrive.live.com/redir?resid=E0A6F6588E499E83!2200&authkey=!AB6kQKArBZTc-64&v=3

I am wondering if I can do something similar in Windows Phone 8. Your inputs on the same is greatly appreciated.

Regards,
Clifford.
Coordinator
Aug 15, 2013 at 6:06 PM
Have you looked at some blog posts / stack overflow? I think http://blog.jerrynixon.com/2011/11/mango-sample-data-validation.html does what you want. Typically if you can do it in Silverlight, it should work in wp
Aug 15, 2013 at 6:29 PM
Thanks a lot Clint, unfortunately Bing never gave me this search result no matter which way I searched for it. I think the information on this website if more than enough for me to figure it out.

Regards,
Clifford.
Coordinator
Aug 15, 2013 at 6:33 PM
For me, it was he 4 or 5 option down on Bing. Searched windows phone data validation. Good to know you are set
Coordinator
Aug 15, 2013 at 8:21 PM