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. }


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>

Code
InputErrorTemplate is as below
HTML / XML
<ControlTemplate x:Key="InputErrorTemplate">  
    <DockPanel>  
        <Border Name="validationBorder" BorderBrush="Red" BorderThickness="2" Padding="1" CornerRadius="3">  
            <Border.Resources>  
                <Storyboard x:Key="_blink">  
                    <ColorAnimationUsingKeyFrames AutoReverse="True" BeginTime="00:00:00" Storyboard.TargetName="validationBorder" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" RepeatBehavior="00:00:02">  
                        <SplineColorKeyFrame KeyTime="00:00:00.5" Value="#00FF0000"/>  
                    </ColorAnimationUsingKeyFrames>  
                </Storyboard>  
            </Border.Resources>  
            <Border.Triggers>  
                <EventTrigger RoutedEvent="FrameworkElement.Loaded">  
                    <BeginStoryboard Storyboard="{StaticResource _blink}" />  
                </EventTrigger>  
            </Border.Triggers>  
            <AdornedElementPlaceholder/>  
        </Border>  
    </DockPanel>  
</ControlTemplate>