2

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"?

7
  • 1
    Try "(?i)^(?!.*TEST).*$". It also seems your "^((?i)(?!TEST)(?!test).)*$" should also work (although a tempered greedy token here is an "overkill"). Commented Feb 27, 2017 at 13:56
  • No luck with that. Seems like any variation of (?i) kills the whole thing. Commented Feb 27, 2017 at 14:13
  • 1
    Does it mean you run this on the client side? (?i) won't work in JS, it will only work in .NET (well, and in some other regex flavors). Commented Feb 27, 2017 at 14:14
  • 1
    Right, JS will never understand (?i). You have to use ^(?!.*[Tt][Ee][sS][tT]).*$ Commented Feb 27, 2017 at 14:44
  • 1
    Posted with some explanations. Commented Feb 27, 2017 at 15:01

2 Answers 2

4

Use an instance of the Regex class with a RegexOptions.IgnoreCase parameter.

Regex validator = new Regex(@"TEST", RegexOptions.IgnoreCase);

if(validator.IsMatch(formValue))
{
    // Do something about this
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.