0

I have a Name input field in xaml and I would like to validate the string length that the user is allowed to insert (up to 14 characters). I tried to do this:

<PropertyViewDescriptor Name="Name" >
   <PropertyViewDescriptor.Validators>
       <TextValuePattern Pattern=".{1,14}" Message="up to 14 characters"/>
   </PropertyViewDescriptor.Validators>
</PropertyViewDescriptor>

But it seems like it checks if the characters are from the set {1,2,3,...,14}. What is the correct pattern for length validation?

Irena
  • 1
  • 2
  • 1
    Are you just looking for like [MaxLength](https://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.maxlength(v=vs.110).aspx) or am I missing something here? – Chris W. Jan 21 '15 at 16:48

2 Answers2

0

You can easily achieve it using a behavior that registers to the textbox.previewkeydown and valdidates the length of the string. You can also use Binding ValidationRules to validate the input string, here is some more info about validation rules: https://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules(v=vs.110).aspx

Amit Raz
  • 5,370
  • 8
  • 36
  • 63
0

I would recomend you to do this using regex.

public class RegexValidationRule : ValidationRule
{
  ... // Declare Regex property and Message property

  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  {
    if(Regex.IsMatch((string)value))
      return ValidationResult.ValidResult;
    else
      return new ValidationResult(false, Message);
  }
}

to accomplish this you use the rule ^([a-zA-Z0-9]){1,14}$.

It's a bit more effort, but it is highly reusable. Using Regex you can validate, basically any kind of text.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
user853710
  • 1,715
  • 1
  • 13
  • 27