zoukankan      html  css  js  c++  java
  • 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));
      }
    }

  • 相关阅读:
    jquery checkbox的相关操作——全选、反选、获得所有选中的checkbox
    js 跳转页面 刷新页面
    一些基本的正则- 手机号正则,邮箱正则,数字正则,字母正则,汉子正则,身份证正则.等
    vue 中使用 国际化(i18n)
    nvm 下载node不会自动下载npm
    angular 自定义组件和form的formControlName 连用
    angular8 搜索组件封装
    vscode 设置缩进 4
    滚动条样式设置
    使用vscode 1. 报在签出前,请清理储存库工作树. 2.拉取代码报错
  • 原文地址:https://www.cnblogs.com/facingwaller/p/1914335.html
Copyright © 2011-2022 走看看