我有一个asp.net MVC应用程序。有一个名为File的实体,它具有名为Name的属性。

using System.ComponentModel.DataAnnotations;

public class File    {
   ...
   [RegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx ..., ErrorMessage = "Invali File Name"]
   public string Name{ get; set; }
   ...
}

有一个RegularExpressionValidator检查文件扩展名。
有没有一种快速的方法可以让我忽略扩展名,而不必在验证表达式中显式添加大写变体?
我需要在服务器端和客户端都使用这个RegularExpressionValidator。
“(?i)”可用于服务器端,但这不适用于客户端

最佳答案

我能想到的一种方法是编写自定义验证属性:

public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
{
    public IgnorecaseRegularExpressionAttribute(string pattern): base("(?i)" + pattern)
    { }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "icregex",
            ErrorMessage = ErrorMessage
        };
        // Remove the (?i) that we added in the pattern as this
        // is not necessary for the client validation
        rule.ValidationParameters.Add("pattern", Pattern.Substring(4));
        yield return rule;
    }
}

然后用它来装饰模型:
[IgnorecaseRegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx", ErrorMessage = "Invalid File Name"]
public string Name { get; set; }

最后在客户端上编写一个适配器:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.validator.unobtrusive.adapters.add('icregex', [ 'pattern' ], function (options) {
        options.rules['icregex'] = options.params;
        options.messages['icregex'] = options.message;
    });

    jQuery.validator.addMethod('icregex', function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        match = new RegExp(params.pattern, 'i').exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
    }, '');
</script>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)
    <input type="submit" value="OK" />
}

当然,您可以将客户端规则外部化为一个单独的javascript文件,这样您就不必在任何地方重复它。

10-06 09:51