代码改变世界

Silverlight杂记输入验证Input validation

2010-12-23 04:18  撞破南墙  阅读(1682)  评论(0编辑  收藏  举报

 binding是一个非常重要的特性,所有的验证显示也都是通过它来

实现的。在Silverlight4中由IDataErrorInfo  and  INotifyDataErrorInfo  interfaces 来实现

1 捕获异常

<TextBox Grid.Row="0" Grid.Column="1"
         Text="{Binding LastName, Mode=TwoWay, 
                      ValidatesOnExceptions=True}" />

public string LastName
{
  get { return _lastName; }
  set
  {
    if (string.IsNullOrEmpty(value))
      throw new Exception("姓不能为空");
        _lastName = value;
    NotifyPropertyChanged("LastName");
  }

2使用INotifyPropertyChanged, IDataErrorInfo 验证和显示

public class Employee : INotifyPropertyChanged, IDataErrorInfo {
    private string _lastName;
    public string LastName {
        get { return _lastName; }
        set {
            if (string.IsNullOrEmpty(value))
                _dataErrors["LastName"] = "Last Name is required";
            else if (value.Trim().Length < 2)
                _dataErrors["LastName"] =
                       "Last Name must be at least 2 letters long.";
            else
                if (_dataErrors.ContainsKey("LastName"))
                    _dataErrors.Remove("LastName");

            _lastName = value;
            NotifyPropertyChanged("LastName");
        }
    }

#region IDataErrorInfo Members

      private string _dataError = string.Empty;

      public string Error {
          get { return _dataError; }
      }

      private Dictionary<string, string> _dataErrors =
                     new Dictionary<string, string>();

      public string this[string columnName] {
          get {
              if (_dataErrors.ContainsKey(columnName))
                  return _dataErrors[columnName];
              else
                  return null;
          }
      }

}

xaml 中

<TextBox Grid.Row="0"
         Grid.Column="1"
         Text="{Binding LastName, Mode=TwoWay, ValidatesOnDataErrors=True}" />

 

3异常验证INotifyDataErrorInfo

IEnumerable INotifyDataErrorInfo.GetErrors(string propertyName)
      {
          if (!string.IsNullOrEmpty(propertyName))
          {
              if (_validationErrors.ContainsKey(propertyName))
                  return _validationErrors[propertyName];
              else
                  return null;
          }
          else
          {
              return _classValidationErrors;
          }
      }

      bool INotifyDataErrorInfo.HasErrors
      {
          get
          {
              if (_classValidationErrors.Count > 0)
                  return true;

              foreach (string key in _validationErrors.Keys)
              {
                  if (_validationErrors[key].Count > 0)
                      return true;
              }

              return false;
          }
      }

      #endregion

4为你的实体类添加属性

   [Required]
  [StringLength(320)]
  [RegularExpression(@"^[a-zA-Z][\w\.&-]*[a-zA-Z0-9]@[a-zA-Z0-9]
  [\w\.-]*[a-zA-Z0-9]\.[a-zA-Z\.]*[a-zA-Z]$")]
  public string EmailAddress { get; set; }
  [Range(0, 20)]
  public int NumberOfChildren { get; set; }

还可以自定义

方法1

public class CustomValidationMethods
{
  public static ValidationResult NameBeginsWithB(string name)
  {
    if (name.StartsWith("B"))
      return ValidationResult.Success;
    else
      return new ValidationResult("Name does not begin with 'B'");
  }
}

[CustomValidation(typeof(CustomValidationMethods),
    "NameBeginsWithB"]
public string LastName { get; set; }

方法2

public class NameBeginsWithBAttribute : ValidationAttribute
{
  protected override ValidationResult IsValid(   
    object value, ValidationContext validationContext)
  {
    if (!(value is string))                            
      return new ValidationResult(
        "Incorrect data type. Expected string"); 
    if (string.IsNullOrEmpty((string)value))     
      return ValidationResult.Success;
    if (((string)value).StartsWith("B"))      
      return ValidationResult.Success;
    else
      return new ValidationResult(
        string.Format("{0} does not begin with 'B'",
        validationContext.DisplayName));
  }
}