How do I add a multi-line parameter to the RegularExpression attribute?

I use:

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

      

to make sure each line of the multiline text box is matched correctly. However, I cannot figure out how to add the global flag and multline flag options. Is this not possible with MVC? What other options do I have?

+3


source to share


3 answers


Doesn't seem to RegularExpressionAttribute

support run parameters, so here it allows (compile checked but not checked):



[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);
    }
}

      

+1


source


You can add an inline option to enable MultiLine without adding the RegexOptions overload to the attribute. This will also ensure that the expression will work in Javascript as well.



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

      

+3


source


This is how you could do it with Regex, basically without relying on a multi-line flag or attribute, instead you explicitly define a regex to allow newlines, but the same pattern should follow

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

      

0


source







All Articles