I am trying to implement ValidationRule to validate that user enters only alphabets
in a TextBox
. My following code is a bit different than the above linked example where the properties Min and Max are the fixed numbers; whereas in my case the property AlphabetsOnly
contains range of alphabets.
Question: In the following part of the MainWindow.xaml
file (shown at the bottom) what should I replace ????
with? I found something similar here, but they have declared a property MustEndWith
that indicates the value should end with a word .def
- that is different than saying all characters must be alphabets.
<Binding.ValidationRules>
<local:AlphabetsOnlyValidationRule AlphabetsOnly="????" />
</Binding.ValidationRules>
Code:
public class AlphabetsOnlyValidationRule : ValidationRule
{
public string AlphabetsOnly { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string sVal = value as string;
if (sVal == null)
{
return new ValidationResult(false, "Please enter some text");
}
if (!sVal.ToList().All(c=>char.IsLetter(c)))
{
return new ValidationResult(false, "First Name should contains alphabets only"));
}
return new ValidationResult(true, null);
}
}
MainWindow.xaml:
<Window x:Class="WPF_DeleteNow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
.....
xmlns:local="clr-namespace:MyWPFProject"
mc:Ignorable="d">
<Window.Resources>
<local:AlphabetsOnlyValidationRule x:Key="AlphabetsOnlyKey"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
.....
</Grid.RowDefinitions>
<TextBox Name="txtFirstName">
<TextBox.Text>
<Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:AlphabetsOnlyValidationRule AlphabetsOnly="??????" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>