viks
viks

Reputation: 23

Validating model with regular expression

Hi I am using a validation like below to ensure I am just working on a csv file.

 [RegularExpression(@"(csv)|(CSV)")]
 public string AttachmentFileName { get; set; }

After form submit model returns a value

AttachmentFileName = "UserMapping.csv"

However I am still getting validation error as:

The field AttachmentFileName must match the regular expression '(csv)|(CSV)'.

Where I am doing error? I tested my expression on website, there it seems to work alright.

Upvotes: 2

Views: 48

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You may fix it by matching the whole string (RegularExpressionAttribute requires a full string match):

[RegularExpression(@"^.*[.][cC][sS][vV]$")]
public string AttachmentFileName { get; set; }

The ^.*[.][cC][sS][vV]$ pattern matches

  • ^ - start of string
  • .* - any 0+ chars
  • [.] - a dot
  • [cC][sS][vV] - csv (case insensitive)
  • $ - end of string.

Upvotes: 1

Related Questions