How to add multiline option on RegularExpression attribute?

后端 未结 3 348
面向向阳花
面向向阳花 2021-01-18 19:37

I am using:

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

to make sure each line of a multiline textbox is properl

相关标签:
3条回答
  • 2021-01-18 19:53

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 20:03

    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}(""|\])?$")]
    
    0 讨论(0)
  • 2021-01-18 20:06

    This is how you would do it with Regex, basically not relying on multiline flag or attribute, instead you explicitly define the regex to allow new lines but the same pattern needs to follow

    [RegularExpression(@"^(""|\[)?[a-zA-Z0-9']{1,125}(""|\])?(?:\r?\n(""|\[)?[a-zA-Z0-9']{1,125}(""|\])?)*$")]
    
    0 讨论(0)
提交回复
热议问题