Monday, August 8, 2011

Validation Rules in WPF


WPF data binding model provides ability to validate user input. You can associate Validation Rule with your Binding as well with MultiBinding.  Binding engine automatically checks whether any ValidationRule associated or not if yes then every time value passes to the source it will applies validation. Validation applies only when target value updates source value (i.e. with TwoWay or OneWayToSource binding modes).

To create validation rule you need to inherit ValidationRule class. This class is abstract class and has abstract method named Validate which returns ValidationResult type.

Below example explains how to associate validation rule to data binding.

<Window x:Class="WpfApplication1.ValidationRuleDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Validation Rule" Height="130" Width="280">
<Window.Resources>
<local:Employee x:Key="EmployeeInformation" />
<local:AgeRangeValidationRule x:Key="ageRangeValidation" />
<local:OnlyDigitsValidationRule x:Key="onlyDigitsValidation" />
<local:NameValidationRule x:Key="nameValidation" />
       
<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="ToolTip"
                Value="{Binding RelativeSource=
                           {x:Static RelativeSource.Self},
                Path=(Validation.Errors)[0].ErrorContent}" />
        </Trigger>
    </Style.Triggers>
</Style>
</Window.Resources>
<Grid Margin="5">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.5*" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition  Height="0.20*"/>
        <RowDefinition Height="0.20*" />
        <RowDefinition Height="0" />
    </Grid.RowDefinitions>
       
    <TextBlock Text="Enter Name: " Grid.Column="0"
                Grid.Row="0" Margin="3"/>
    <TextBox Name="Name" Grid.Column="1"
                Grid.Row="0" Height="30" Margin="3">
        <TextBox.Text>
            <Binding Source="{StaticResource EmployeeInformation}"
                        Path="Name">
                <Binding.ValidationRules>
                    <local:NameValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    <TextBlock Text="Enter Age: " Grid.Column="0"
                Grid.Row="1" Margin="3"/>
    <TextBox Name="Age" Grid.Column="1"
                Grid.Row="1" Height="30" Margin="3">
        <TextBox.Text>
            <Binding Source="{StaticResource EmployeeInformation}"
                        Path="Age">
                <Binding.ValidationRules>
                    <local:OnlyDigitsValidationRule />
                    <local:AgeRangeValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</Grid>
</Window>

Code Behind
public class Employee : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }
    private int age;
    public int Age
    {
        get { return age; }
        set { age = value; OnPropertyChanged("Age"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

Validation Rule classes
public class NameValidationRule :ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        string name = value.ToString();
        if (name.All(c=> char.IsLetter(c) || c== ' '))
            return new ValidationResult(true, null);
        return new ValidationResult(false, "Please enter only alphabets");
    }
}
public class AgeRangeValidationRule: ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        int age = int.Parse(value.ToString());
           
        if (age >= 18 && age <= 35)
        {
            return new ValidationResult(true, null);
        }
           
        return new ValidationResult(false,
                      "Please enter Age between 18 to 35");
    }
}

public class OnlyDigitsValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        if (!value.ToString().All(c => char.IsDigit(c)))
            return new ValidationResult(false,
                          "Please enter only digits");

        return new ValidationResult(true, null);
    }
}














In above example, Name and Age textbox are bound with Name and Age property of Employee class. Name property implements NameValidationRule and Age property implements two validation rules first one is OnlyDigitsValidationRule and second AgeRangeValidationRule.

NameValidationRule allows only alphabets and space it means you can’t enter other than alphabets inside Name textbox. While AgeRangeValidationRule allows age between 18 to 35 and OnlyDigitsValidationRule allows only digits to Age textbox.

Age property implements two validation rules so when multiple validation rules are associated with binding then they are validated in sequence means as per the association order. As per above example OnlyDigitsValidationRule validates first and followed by AgeRangeValidationRule. 

Related links -

15 comments:

  1. i want source code file of this validation urgently

    ReplyDelete
  2. Hello Lalit,

    I have uploaded all the code required for validating WPF fields on this post itself. I don't have any separate solution for the same.

    ~Mitesh

    ReplyDelete
  3. Your information about asp is really interesting and innovative. Also I want you to share latest updates about asp. Can you update it in your website? Thanks for sharing
    Dot net training institute in Chennai

    ReplyDelete
  4. Thanks for sharing these niche piece of coding to our knowledge. Here, I had a solution for my inconclusive problems & it’s really helps me a lot keep updates…DOT NET Training in Chennai

    ReplyDelete
  5. Dot Net Training Chennai

    Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Training in Chennai reach FITA, rated as No.1 Dot Net Training Institute in Chennai.

    Dot Net Course in Chennai




    ReplyDelete
  6. I have read your blog and i got a very useful and knowledgeable information from your blog.its really a very nice article. I did Loadrunner Training in Chennai. This is really useful for me. Suppose if anyone interested to learn Manual Testing Training in Chennai reach FITA academy located at Chennai Velachery.

    regards...

    Software Testing Training in Chennai

    ReplyDelete
  7. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. CCNA Training in chennai | CCNA Training chennai | CCNA course in chennai | CCNA course chennai

    ReplyDelete

  8. Thanks for sharing this information. Java is one of the popular object oriented programming language used for many of the multinational corporation. So learning Java Training in Chennai is really helpful to make a bright future.

    ReplyDelete
  9. Salesforce is a cloud based CRM software. Today's most of the IT industry use this software for customer relationship management. To get more details about salesforce please refer this site.

    Regards..
    Salesforce Administrator Training in Chennai

    ReplyDelete
  10. Nice post. Oracle is a relational database management system produced by oracle corporation. Nowadays most of the multinational companies used this oracle database for storing and managing their data's and programs. So learning Oracle Training in Chennai is one of the best idea to make a bright career.

    ReplyDelete
  11. Nice information. Salesforce is a most powerful CRM tool used for manage all customers including potential customers. Salesforce Training in Chennai offering this course with experienced professionals.

    ReplyDelete
  12. Really nice post. SEO is one of the digital marketing techniques used for improve the website ranking in search engine result page. To know more details please call 9003623340.
    Regards..
    SEO Training in Chennai

    ReplyDelete
  13. Nice post. PHP is one of the server side scripting language mainly used for designing website. So learning PHP Training Chennai is really useful to make a better career.
    Regards..
    HTML5 Training

    ReplyDelete
  14. I get a lot of great information from this blog. Thank you for your sharing this informative blog. Just now I have completed hadoop certification course at a leading academy. If you are interested to learn Hadoop Training in Chennai visit FITA IT training and placement academy.

    ReplyDelete
  15. Hi friends,This is Johnson from Chennai.Thanks for sharing this informative blog. I did Unix certification course in Chennai at Fita academy. This is really useful for me to make a bright career.
    Regards..
    Unix Training

    ReplyDelete