XAML字符串长度验证

时间:2015-01-21 15:58:59

标签: wpf validation xaml

我在xaml中有一个Name输入字段,我想验证允许用户插入的字符串长度(最多14个字符)。 我试着这样做:

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

但似乎检查字符是否来自集合{1,2,3,...,14}。 长度验证的正确模式是什么?

2 个答案:

答案 0 :(得分:0)

您可以使用注册到textbox.previewkeydown的行为轻松实现它,并对字符串的长度进行操作。您还可以使用Binding ValidationRules验证输入字符串,以下是有关验证规则的更多信息:https://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules(v=vs.110).aspx

答案 1 :(得分:0)

我建议你使用正则表达式来做这件事。

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);
  }
}

要完成此操作,请使用规则^([a-zA-Z0-9]){1,14}$

它需要更多的努力,但它是高度可重复使用的。使用Regex,您可以验证基本上任何类型的文本。