Search code examples
c#regexasp.net-mvcmodelattributemultilinestring

Regular expression for multiple lines in MVC Model attribute


Uhg ... I suck at regular expressions.

I'm trying to write a regex that will match one or more valid Guids in .NET, separated by new-line characters, for use in an MVC model.

Here is the model property, as I have it now:

[Required]
[Editable(true)]
[DataType(DataType.MultilineText)]
[Display(Name = "Audit Result Global Ids")]
[RegularExpression(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", ErrorMessage = "Audit Result Global Ids must be a list of one or more valid GUIDs.")]
public List<Guid> AuditResultGlobalIds { get; set; }

Here is a sample of what I'm trying match ..

C835EFF5-65D8-4F1B-824D-CD3FD1A04D77
A1FEFACA-6130-4E0A-BAC2-F101C2F4554C
ACD3D3FC-E841-45E9-A081-C113231E56EF

I have a great pattern for a single RegEx:

@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$"

I just need the multi-line part.


UPDATE: Here is the exact solution I ended up going with.

Custom validation class:

using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;

/// <summary>
/// The regular expression on list elements.
/// </summary>
public class RegularExpressionOnListElements : RegularExpressionAttribute
{
    /// <summary>
    /// Initializes a new instance of the <see cref="RegularExpressionOnListElements"/> class.
    /// </summary>
    /// <param name="pattern">
    /// The pattern.
    /// </param>
    public RegularExpressionOnListElements(string pattern)
        : base(pattern)
    {
    }

    #region Public Methods and Operators

    /// <summary>
    /// The is valid.
    /// </summary>
    /// <param name="value">
    /// The value.
    /// </param>
    /// <param name="validationContext">
    /// the validationContext
    /// </param>
    /// <returns>
    /// The <see cref="ValidationResult "/>.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string[] lines = Regex.Split(value.ToString(), "\r\n");

            if (lines.Length > 0)
            {
                if (!lines.All(elem => base.IsValid(elem)))
                {
                    return new ValidationResult(
                        "Audit Result Global Ids must be a list of one or more valid GUIDs.");
                }
            }
        }

        return ValidationResult.Success;
    }

    #endregion
}

Model propery:

/// <summary>
///     Gets or sets the list of audit result global ids.
/// </summary>
[Editable(true)]
[DataType(DataType.MultilineText)]
[Display(Name = "Audit Result Global Ids")]
[RegularExpressionOnListElements(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")]
public string AuditResultGlobalIds { get; set; }

Solution

  • You can make a custom validation attribute.

    RegularExpressionOnList

    public class RegularExpressionOnListElements : RegularExpressionAttribute
    {
        public RegularExpressionOnListElements(string pattern)
            : base(pattern)
        {
        }
    
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.All(elem => base.IsValid(elem));
            }
            return true;
        }
    }
    

    Usage:

    [Required]
    [Editable(true)]
    [DataType(DataType.MultilineText)]
    [Display(Name = "Audit Result Global Ids")]
    [RegularExpressionOnListElements(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", ErrorMessage = "Audit Result Global Ids must be a list of one or more valid GUIDs.")]
    public List<Guid> AuditResultGlobalIds { get; set; }
    

    Note: Code have not been tested.