RegularExpression use variables for same string pattern attribute C#

Viewed 84

Can we replace the string pattern @"^[a-zA-Z''-'\s]{1,40}$" to use as a variable in an attribute?

I tried setting the pattern to a string, but when I use [RegularExpression...] to use the variable it doesn't work. I want to use a variable since it's the same regex Format.

  private static String regexFormat = @"^[a-zA-Z''-'\s]{1,40}$";

or

   private static String regexFormat = "^[a-zA-Z''-'\s]{1,40}$";

  
    [Display(Name = "Name", Description = "First Name + Last Name.")]
    [Required(ErrorMessage = "First Name is required.")]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
        "Numbers and special characters are not allowed in the name.")]


    [Required(ErrorMessage = "Last Name is required.")]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
        "Numbers and special characters are not allowed in the name.")]

I want something like this

[RegularExpression(regexFormat, ErrorMessage ="Error in Format")]

is this possible, if so how?

1 Answers

Attributes require the information to be available during the compile time of the application and are not dynamic and are locked in, which is needed for the compiler.

Making the pattern to be a const (a compile-time constant) allows such a value to later be calculated/used at run-time and which can be set in the constructor or field initializer/attribute. Whereas readonly is read only once when assigned, hence not viable.

Usage of const should work for you in this situation.

Related