Search code examples
c#wpfvalidationxamlvalidationrules

ValidationRule with UpdateSourceTrigger=LostFocus not firing when textbox loses focus


I am attempting to implement validation for form data in a WPF application.

View

<StackPanel Orientation="Horizontal" Margin="0 5 0 5">
    <TextBlock Style="{StaticResource FormLabel}" Text="Agency:"/>
    <TextBox x:Name="agency" Style="{StaticResource InputBox}" Margin="10 0 10 0"
                    Width="214" TabIndex="1" >
        <Binding Path="Agency" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <validationrules:RequiredValidationRule FieldName="Agency"/>
            </Binding.ValidationRules>
        </Binding> 
    </TextBox>
</StackPanel>

Validation Rule

public class RequiredValidationRule : ValidationRule
{
    public static string GetErrorMessage(string fieldName, object fieldValue, object nullValue = null)
    {
        string errorMessage = string.Empty;
        if (nullValue != null && nullValue.Equals(fieldValue))
            errorMessage = string.Format("You cannot leave the {0} field empty.", fieldName);
        if (fieldValue == null || string.IsNullOrEmpty(fieldValue.ToString()))
            errorMessage = string.Format("You cannot leave the {0} field empty.", fieldName);
        return errorMessage;
    }

    public string FieldName { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string error = GetErrorMessage(FieldName, value);
        if (!string.IsNullOrEmpty(error))
            return new ValidationResult(false, error);
        return ValidationResult.ValidResult;
    }
}

I placed a breakpoint inside the validation rule and found that if I tab or click into the TextBox and then click or tab away, the validation rule doesn't fire. However, if I tab or click into the TextBox, type something, delete it and then tab away it works.

I've verified with dummy events for GotFocus and LostFocus that the TextBox focus is changing appropriately.

I need the validation rule to fire if the box loses focus even if nothing is entered. Is it possible to do that and where am I going wrong?


Solution

  • When you declare a validation rule, set ValidatesOnTargetUpdated to true.

    <validationrules:RequiredValidationRule ValidatesOnTargetUpdated="True" FieldName="Agency"/>