正则表达式属性——如何使它对客户端验证不敏感?

时间:2022-12-09 12:22:23

I have a string that I use for client side validation:

我有一个字符串用于客户端验证:

private const String regex = @"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";

I use this string in my [RegularExpression(regex, ErrorMessage = "invalid")] attribute.

我在[正则表达式(regex, ErrorMessage = "invalid")]属性中使用此字符串。

I know that the /i flag for a Javascript regex is used to make it case insensitive, but just tacking it on to the end of my regex (i.e. @"^....$/i" isn't working - the regex validation fails completely, regardless of what is entered (valid or not).

我知道/我为一个Javascript正则表达式是用来使它不分大小写,但只是附加的结束我的正则表达式(例如@”^ ....$/i“不起作用——无论输入什么(有效与否),regex验证都完全失败。

What am I missing?

我缺少什么?

3 个解决方案

#1


8  

private const String regex = @"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";

#2


32  

I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.

我创建了这个属性,允许您指定RegexOptions。编辑:它还集成了不显眼的验证。客户端只会遵守RegexOptions。多行和RegexOptions。因为这是JavaScript支持的。

[RegularExpressionWithOptions(@".+@example\.com", RegexOptions = RegexOptions.IgnoreCase)]

C#

c#

public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
    public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }

    public RegexOptions RegexOptions { get; set; }

    public override bool IsValid(object value)
    {
        if (string.IsNullOrEmpty(value as string))
            return true;

        return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
    }

    public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "regexwithoptions"
        };

        rule.ValidationParameters["pattern"] = Pattern;

        string flags = "";
        if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
            flags += "m";
        if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
            flags += "i";
        rule.ValidationParameters["flags"] = flags;

        yield return rule;
    }
}

JavaScript

JavaScript

(function ($) {

    $.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
        options.messages['regexwithoptions'] = options.message;
        options.rules['regexwithoptions'] = options.params;
    });

    $.validator.addMethod("regexwithoptions", function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        var reg = new RegExp(params.pattern, params.flags);
        match = reg.exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
    });

})(jQuery);

This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators

安东尼·史蒂文斯的这篇文章帮助我实现了这个目标:ASP。NET MVC 3使用自定义验证器进行不显眼的Javascript验证

#3


15  

In C# you can inline some regex options. To specify the option to ignore case you would add (?i) to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator I doubt it; the regex should be vanilla enough to work for both engines.

在c#中,您可以内联一些regex选项。要指定忽略大小写的选项,您需要在模式的开头添加(?i)。但是,我不确定正则表达式属性将如何处理这个问题,以及它是否处理客户端的翻译。从我在ASP中的经验来看。NET的正则表达式验证器我对此表示怀疑;regex应该足够适用于两个引擎。

In any case if it was valid it would look like this:

无论如何,如果它是有效的,它会是这样的:

@"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"

#1


8  

private const String regex = @"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";

#2


32  

I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.

我创建了这个属性,允许您指定RegexOptions。编辑:它还集成了不显眼的验证。客户端只会遵守RegexOptions。多行和RegexOptions。因为这是JavaScript支持的。

[RegularExpressionWithOptions(@".+@example\.com", RegexOptions = RegexOptions.IgnoreCase)]

C#

c#

public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
    public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }

    public RegexOptions RegexOptions { get; set; }

    public override bool IsValid(object value)
    {
        if (string.IsNullOrEmpty(value as string))
            return true;

        return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
    }

    public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "regexwithoptions"
        };

        rule.ValidationParameters["pattern"] = Pattern;

        string flags = "";
        if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
            flags += "m";
        if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
            flags += "i";
        rule.ValidationParameters["flags"] = flags;

        yield return rule;
    }
}

JavaScript

JavaScript

(function ($) {

    $.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
        options.messages['regexwithoptions'] = options.message;
        options.rules['regexwithoptions'] = options.params;
    });

    $.validator.addMethod("regexwithoptions", function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        var reg = new RegExp(params.pattern, params.flags);
        match = reg.exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
    });

})(jQuery);

This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators

安东尼·史蒂文斯的这篇文章帮助我实现了这个目标:ASP。NET MVC 3使用自定义验证器进行不显眼的Javascript验证

#3


15  

In C# you can inline some regex options. To specify the option to ignore case you would add (?i) to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator I doubt it; the regex should be vanilla enough to work for both engines.

在c#中,您可以内联一些regex选项。要指定忽略大小写的选项,您需要在模式的开头添加(?i)。但是,我不确定正则表达式属性将如何处理这个问题,以及它是否处理客户端的翻译。从我在ASP中的经验来看。NET的正则表达式验证器我对此表示怀疑;regex应该足够适用于两个引擎。

In any case if it was valid it would look like this:

无论如何,如果它是有效的,它会是这样的:

@"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"