Andy Andy -4 years ago 134
C# Question

How to add case insensitive form field validation in C#?

I'm trying to add validation to a form field so that if it contains a certain word, an error is displayed. At the moment I have this:

Validation.Add("field-1", Validator.Regex("^((?!TEST)(?!test).)*$", "Field may not contain 'test'"));


This works fine for "TEST" and "test", but won't prevent someone entering "tESt".

I've tried adding the case insensitive flag, but this made the regex stop working completely:

Validation.Add("field-1", Validator.Regex("/^((?!TEST)(?!test).)*$/i", "Field may not contain 'test'"));


I also read here that (?i) can be used to ignore case, but that didn't work either - maybe I'm putting it in the wrong place:

Validation.Add("field-1", Validator.Regex("^((?i)(?!TEST)(?!test).)*$", "Field may not contain 'test'"));


Is this doable without adding every possible variation of "test"?

Answer Source

It appears that that your regex is handled on the client side. JavaScript RegExp does not support (?i) inline modifier (it does not support any inline modifiers, even the XRegExp library), so the only way out is to spell out all the letter cases using character classes:

Validation.Add("field-1", Validator.Regex("^(?!.*[Tt][Ee][sS][tT]).*$", "Field may not contain 'test'"));

Note that your tempered greedy token is too resource consuming a pattern, it is easier to use a simple negative lookahead here. If you need to support multiline strings, replace the . with [\s\S] character class.

Details:

  • ^ - start of string
  • (?!.*[Tt][Ee][sS][tT]) - there cannot be any Test or TesT, etc., after any 0+ chars
  • .* - any 0+ chars, as many as possible
  • $ - end of string.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download