Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiline option on RegularExpression attribute?

I am using:

[RegularExpression(@"^(""|\[)?[a-zA-Z0-9']{1,125}(""|\])?$")]

to make sure each line of a multiline textbox is properly matched. I cannot however figure out how to add the global flag and multline flag options. Is it impossible with MVC? What other options do I have?

like image 327
Darren Avatar asked Mar 13 '12 18:03

Darren


2 Answers

You can add an inline option to enable MultiLine without having to add a RegexOptions overload to the Attribute. That also ensures the expression will work in Javascript as well.

    [RegularExpression(@"(?m)^(""|\[)?[a-zA-Z0-9']{1,125}(""|\])?$")]
like image 124
jessehouwing Avatar answered Oct 03 '22 15:10

jessehouwing


It doesn't look like the RegularExpressionAttribute supports passing options, so here's one that allows it (compile checked but not tested):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, 
                         AllowMultiple = false)]
public class RegExAttribute : ValidationAttribute
{
    public string Pattern { get; set; }
    public RegexOptions Options { get; set; }

    public RegExAttribute(string pattern) : this(pattern, RegexOptions.None) { }
    public RegExAttribute(string pattern, RegexOptions options)
    {
        Pattern = pattern;
        Options = options;
    }

    public override bool IsValid(object value)
    {
        return Regex.IsMatch(value.ToString(), Pattern, Options);
    }
}
like image 45
M.Babcock Avatar answered Oct 03 '22 15:10

M.Babcock