【问题标题】:Validating models using RegularExpression annotation使用正则表达式注释验证模型
【发布时间】:2014-10-28 22:40:58
【问题描述】:

我在我的 web api 项目中添加了一个过滤器,以验证从客户端传递的所有模型。为了验证模型,我使用了数据注释。除非我使用正则表达式注释,否则一切似乎都可以正常工作。

这是我的 api 中的过滤器:

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }

这是未正确验证的模型属性:

    [Required]
    [MinLength(8)]
    [StringLength(255)]
    [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)", ErrorMessage = "Password must contain at least one capital letter and one number")]
    public string Password { get; set; }

无论我在字符串中传递什么值,我都会不断收到错误消息。对此的任何帮助将不胜感激。

【问题讨论】:

    标签: c# .net regex asp.net-web-api data-annotations


    【解决方案1】:

    试试这个:

    ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).*$
    

    当密码格式正确时,您的表达式可能会返回 null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多