Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am unable to get a WPF ValidationRule to detect an empty TextBox.

My cut-down code is as follows:
public class NonEmptyStringValidator : ValidationRule
{
    public override ValidationResult Validate( object value, CultureInfo cultureInfo )
    {
        ValidationResult validationResult = new ValidationResult( false, "Value cannot be empty." );
        if( value != null )
        {
            string valueAsString = value as string;
            if( valueAsString.Length > 0 )
                validationResult = ValidationResult.ValidResult;
        }
        return validationResult;
    }
}

My cut-down XAML is as follows:
XML
<TextBox 
    <TextBox.Text>
        <Binding Path="SelectedUser.Username" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <u:NonEmptyStringValidator/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

A breakpoint placed inside the Validate() function reveals that the code is not run until there is something in the TextBox. Is there a way to get it to work to detect an empty string?

What I have tried:

I have tried various values for UpdateSourceTrigger.

I have also tried hooking into the LostFocus event for the TextBox and writing code to handle this manually. This gets very messy because one thing I need to do is keep focus on the TextBox until is has something in it, and calling Focus() seems to cause the LostFocus event to fire again, which is something else I don't understand.
Posted
Updated 19-Sep-17 11:59am
v2

1 solution

 
Share this answer
 
Comments
Patrick Skelton 20-Sep-17 4:31am    
Thank you for your answer.

In your Google search, I see the word 'manually'. I confess I didn't try this because this seemed like the exact opposite of what I was trying to do.

The search link seems like a ridiculous amount of code for something so simple. The second contained reference to the very promisingly named 'ValidatesOnTargetUpdated'. This seems to work but I get a null reference exception in the XAML design view when I add it to the validation rule. I tried putting it in the constructor for the ValidationRule, which again works but again I get the same error in the XAML designer.
Graeme_Grant 20-Sep-17 4:36am    
Yes, this is not the default "automatic" behavior, you want to "manually" do it, hence why I used it in the search.

The first, is as the title suggests, it will do all the hard work for you forcing validation on all controls in the visual graph, not just one. The second only does one.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900