When my textbox is empty/null, i need to display “Required”.
In my xaml:
<TextBox Name="txtLastName" Grid.Column="1" Grid.Row="1" Margin="3">
<TextBox.Text>
<Binding Path="LastName">
<Binding.ValidationRules>
<validators:Contractor
MinimumLength="1"
MaximumLength="40"
ErrorMessage="Required" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
In my class:
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyPropertyChanged("LastName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private int _minimumLength = -1;
private int _maximumLength = -1;
private string _errorMessage;
public int MinimumLength
{
get { return _minimumLength; }
set { _minimumLength = value; }
}
public int MaximumLength
{
get { return _maximumLength; }
set { _maximumLength = value; }
}
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value,CultureInfo cultureInfo)
{
ValidationResult result = new ValidationResult(true, null);
string inputString = (value ?? string.Empty).ToString();
if (inputString.Length < this.MinimumLength || value==null ||
(this.MaximumLength > 0 &&
inputString.Length > this.MaximumLength))
{
result = new ValidationResult(false, this.ErrorMessage);
}
return result;
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
What i get is the textbox turns into red border when the data is null/empty and i am not able to see the “Required” error message, any thoughts?
(The red border is the default behavior of a
TextBoxwhen the attached propertyValidation.HasErroris true.In order to display the error messsage you’ll have to do that yourself by binding to
Validation.Errors.
Validation.Errorsis a list of error from each validator applied to theTextBox.Now in your case you only have one validator so in order to get the error message you need to bind to
Validation.Errors[0].ErrorContentExample