• Silverlight杂记输入验证Input validation


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

  • 相关阅读:
    Asp.Net Core MVC + Code First + Mysql 项目创建以及相关配置
    linux安装 docker compose v2
    压缩、解压 解决 客户端查询大批量数据时等待时间过长的问题
    c# 通过经纬度 查询地址、区域信息
    excel 文件转 dataset ,jqgrid 中 模糊查询与下拉联动的实现
    jqgrid mvc 导出excel
    SQL学习笔记三表的字段操作
    SQL学习笔记高级教程
    安装docker
    SQL学习笔记一数据类型
  • 原文地址:https://www.cnblogs.com/facingwaller/p/1914335.html
Copyright © 2020-2023  润新知