I use RegularExpressionAttribute on my EF meta data like so:
[RegularExpression("[A-Z]+")]
public string Code { get; set; }
And it correctly does not let me enter anything other than A-Z anywhere in the field.
Elsewhere I want to use the same reg expressions in code, so I turned to Regex like so:
var regex = new Regex("[A-Z]+");
Console.WriteLine(regex.IsMatch("B")); //true
Console.WriteLine(regex.IsMatch("1")); //false
Console.WriteLine(regex.IsMatch("A1")); //true - why?
Also RegexStringValidator works the same as Regex.
What am I doing wrong?
That regex says to match one or more upper case latin letters. And “
A1” contains an upper case latin letter.By default regexes match anywhere in the string. To match the whole string start with a “
^” start of string anchor and end with a “$” end of string anchor:will show
false.(There are a whole set of anchors in .NET regular expressions.)