Display Custom Error Message in RadMaskedInput
Environment
Product | RadMaskedInput for WPF |
Description
Implement custom validation by adding a ValidationError in code.
Solution
If you want to mark the state of the control as invalid and display an error message in the RadMaskedInput controls and you do not want to throw validation exceptions or use data annotations, you can manually set a validation error in code by using the ValidationError class and the Validation.MarkInvalid method.
private void MaskedInput_ValueChanged(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
var input = sender as RadMaskedTextInput;
if (input.Value == "123")
{
var rule = new ExceptionValidationRule();
ValidationError validationError = new ValidationError(rule, this.MaskedInput.GetBindingExpression(RadMaskedTextInput.ValueProperty));
validationError.ErrorContent = "The input is invalid!";
Validation.MarkInvalid(this.MaskedInput.GetBindingExpression(RadMaskedTextInput.ValueProperty), validationError);
}
else
{
Validation.ClearInvalid(this.MaskedInput.GetBindingExpression(RadMaskedTextInput.ValueProperty));
}
}
For this approach to work as expected, a binding to the Value property of the control needs to be set.