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 -

42 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
  16. There are lots of information about latest technology and how to get trained in them, like Big Data Training in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies(Big Data Training). By the way you are running a great blog. Thanks for sharing this. cloud computing training in chennai

    ReplyDelete
  17. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

    ReplyDelete
  18. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

    ReplyDelete
  19. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

    ReplyDelete
  20. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks
    for taking the time to discuss this, I feel happy about it and I love learning more about this topic
    Android Training In Chennai In Chennai

    ReplyDelete
  21. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

    ReplyDelete
  22. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

    ReplyDelete
  23. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    ReplyDelete
  24. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

    ReplyDelete
  25. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

    ReplyDelete
  26. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

    ReplyDelete
  27. This is exactly what I was searching for. Awesome post. Thanks a bunch. Helped me in taking class for my students. Wish to follow your posts, keep writing! God Bless!
    Shashaa
    Dot Net training institutes in Chennai | Dot Net training institutes in Chennai | Dot Net training institutes in Chennai

    ReplyDelete
  28. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:
    Oracle Training in Chennai

    ReplyDelete
  29. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Oracle DBA Training in Chennai

    ReplyDelete
  30. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
    Oracle RAC Training in Chennai

    ReplyDelete
  31. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.
    SalesForce Training in Chennai

    ReplyDelete
  32. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Java Training in Chennai

    ReplyDelete
  33. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    PHP Training in Chennai

    ReplyDelete
  34. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me..
    Android Training in Chennai

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    SAP Training in Chennai

    ReplyDelete
  37. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training in Chennai

    ReplyDelete
  38. It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to Selenium Training in Chennai reach Greens Technology training and placement academy.
    selenium Training in Chennai

    ReplyDelete
  39. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training In Chennai | oracle apps financials Training In Chennai | advanced plsql Training In Chennai

    ReplyDelete
  40. Hello admin, thank you for your informative post on hadoop training in Chennai. It helped a lot in training my students during our hadoop training Chennai sessions. We at Fita, provide big data training in Chennai for students who are interested in choosing a career in big data.

    ReplyDelete
  41. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai

    ReplyDelete
  42. Best iOS Training Institute In Chennai It’s too informative blog and I am getting conglomerations of info’s about Oracle interview questions and answer .Thanks for sharing, I would like to see your updates regularly so keep blogging.

    ReplyDelete