【问题标题】:Custom Regular Expression not validating on the client side自定义正则表达式不在客户端验证
【发布时间】:2016-04-25 16:27:59
【问题描述】:

我已经构建了一个自定义属性来在客户端验证正十进制值。问题是当我将正则表达式直接应用于属性时,它可以正常工作,但是当我使用自定义属性时,它就不起作用了。

工作模式:

    [RegularExpression(@"^(?!0?(,0?0)?$)([0-9]{0,3}(,[0-9]{1,2})?)?$", ErrorMessage = "Largura inválida.")]
    [Required(ErrorMessage = "Largura obrigatória.")]
    [Display(Name = "Formato Aberto")]
    public decimal SizeOpenedWidth { get; set; }

自定义属性:

public class PositiveDecimalAttribute : RegularExpressionAttribute
{
    public PositiveDecimalAttribute() : base("^(?!0?(,0?0)?$)([0-9]{0,3}(,[0-9]{1,2})?)?$") { }
}

集成在属性中:

    [PositiveDecimal(ErrorMessage = "Largura inválida.")]
    [Required(ErrorMessage = "Largura obrigatória.")]
    [Display(Name = "Formato Aberto")]
    public decimal SizeOpenedWidth { get; set; }

在第二个中,客户端验证显示错误消息:

The field Formato Aberto must be a number.

是否需要在客户端验证中集成新属性?

【问题讨论】:

  • 你在global.asax注册了吗?
  • 您好,谢谢,不。我必须在 global.asax 中包含什么?
  • Application_Start() - 添加DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAttribute), typeof(RegularExpressionAttributeAdapter));
  • 就这样? :) 它的工作!我必须为每个自定义属性都这样做吗?
  • 如果它继承自现有的RegularExpressionAttribute,那么是的

标签: c# regex asp.net-mvc validation


【解决方案1】:

您需要在global.asax 中注册您的属性。在其Application_Start() 方法中,添加以下代码:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAtt‌​ribute), typeof(RegularExpressionAttributeAdapter));

【讨论】:

  • 感谢斯蒂芬的帮助;)
猜你喜欢
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2016-03-29
相关资源
最近更新 更多