Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

regex - RegularExpressionAttribute - How to make it not case sensitive for client side validation?

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

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

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

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).

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

(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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...