Reputation: 180777
I have a text box whose Text property is set like this:
<TextBox.Text>
<Binding Path="PointOfContact">
<Binding.ValidationRules>
<local:NotEmptyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
The NotEmptyValidationRule
class looks like this:
public class NotEmptyValidationRule : ValidationRule
{
public string Message { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (string.IsNullOrWhiteSpace(value?.ToString()))
{
return new ValidationResult(false, Message ?? "A value is required");
}
return ValidationResult.ValidResult;
}
}
Assuming there are several other controls on my form that have validation rules similarly-defined, how do I get the form to validate all of the rules on all of the controls when the Save button is clicked?
Upvotes: 0
Views: 328
Reputation: 886
I have achieved this by implementing the INotifyDataErrorInfo
interface on my model and mapping validation instances to properties. On an attempted save if any of the validation checks fail you would invoke the event ErrorsChanged
which would include the property name of whichever field was invalid. You'll also have to set the flag ValidatesOnNotifyDataErrors
to true on the binding. I'm guessing you are hoping to do this without keeping separate instances of the validators but I'm not aware of another way. You can also optionally remove the validator defined in the xaml as it's redundant.
<TextBox.Text>
<Binding Path="PointOfContact">
<Binding.ValidatesOnNotifyDataErrors>True</Binding.ValidatesOnNotifyDataErrors>
<Binding.ValidationRules>
<local:NotEmptyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
Upvotes: 1