Validations in WPF

Validating textboxes in WPF. The validtion is checked at LostFocus event of TextBox
  1. public void ValidateTextbox(ref TextBox ctrltxt, string p)  
  2.       {  
  3.           int count = 0;  
  4.           string errormessage=string.Empty;  
  5.           BindingExpression expression = ctrltxt.GetBindingExpression(TextBox.TextProperty);  
  6.           expression.UpdateSource();  
  7.           if (true// check validation condition or reg expression here  
  8.           {  
  9.                   ValidationError error = new ValidationError(new ExceptionValidationRule(), expression, errormessage, null);  
  10.                   Validation.MarkInvalid(expression, error);  
  11.   
  12.           }  
  13.   
  14.       }  


XAML code for the TEXTBOX is as below

  1. <TextBox Name="FieldName" HorizontalAlignment="Stretch"   
  2.                     VerticalAlignment="Stretch"   
  3.                     Text="{Binding Path=DisplayData, ValidatesOnDataErrors=True ,NotifyOnValidationError=True , UpdateSourceTrigger=LostFocus, ValidatesOnExceptions=True}"  
  4.                     Grid.Column="1"   
  5.                     Margin="4,4,4,4" Validation.ErrorTemplate="{StaticResource InputErrorTemplate}"  >  
  6.                                    </TextBox>  

InputErrorTemplate is as below
  1. <ControlTemplate x:Key="InputErrorTemplate">  
  2.     <DockPanel>  
  3.         <Border Name="validationBorder" BorderBrush="Red" BorderThickness="2" Padding="1" CornerRadius="3">  
  4.             <Border.Resources>  
  5.                 <Storyboard x:Key="_blink">  
  6.                     <ColorAnimationUsingKeyFrames AutoReverse="True" BeginTime="00:00:00" Storyboard.TargetName="validationBorder" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" RepeatBehavior="00:00:02">  
  7.                         <SplineColorKeyFrame KeyTime="00:00:00.5" Value="#00FF0000"/>  
  8.                     </ColorAnimationUsingKeyFrames>  
  9.                 </Storyboard>  
  10.             </Border.Resources>  
  11.             <Border.Triggers>  
  12.                 <EventTrigger RoutedEvent="FrameworkElement.Loaded">  
  13.                     <BeginStoryboard Storyboard="{StaticResource _blink}" />  
  14.                 </EventTrigger>  
  15.             </Border.Triggers>  
  16.             <AdornedElementPlaceholder/>  
  17.         </Border>  
  18.     </DockPanel>  
  19. </ControlTemplate>