Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Hello;
I am trying to figure out a way of validating a text area that must contain at least a couple of words with a mix of and/or statements.
Essentially I am looking for a validation that looks for certian words in a sentence. Example, text area must contain word1 or word2 but also must contain word3 and word4.
Can this be done with Regex? Any pointers on how to start?
Thanks;
-Ryan
Comments
Comment #1
rbrownellThis can be achieved with the regular expressions...
Examples
"This"
^(?=.*?\bRehearsal\b).*$
Validates for the word Rehersal.
"This or This or This"
^(?=.*?\b(Rehearsal|Matinee|Performance)\b).*$
Validates for at least one of the words Rehersal, or Matinee, or Performance.
"This and This and This"
^(?=.*?\bRehearsal\b)(?=.*?\bMatinee\b)(?=.*?\bPerformance\b).*$
Validates only if all the words Rehearsal, Matinee, and Performance are present.
"This or This, This or This, and This"
^(?=.*?\b(Load In|Setup)\b)(?=.*?\b(Load Out|Teardown)\b)(?=.*?\bPerformance\b).*$
Validates only if either Load In or Setup is present, and Load Out or Teardown is present and only if Performance is present.
"Not This"
^((?!Matinee).)*$
Validates only if Matinee is not present.
"Not This or This or This"
^((?!Rehearsal|Matinee|Performance).)*$
Validates only if neither Rehearsal, nor Matinee, nor Performance are present.
"This, This or This, and This or This, but Not This or This
^(?=.*?\bPerformance\b)(?=.*?\b(Load In|Setup)\b)(?=.*?\b(Load Out|Teardown)\b)((?!Matinee|Rehearsal).)*$
Validates only if Performance, and Load In or Setup, and Load Out or Teardown is present but won't validate if Matinee or Rehearsal is present.
Comment #2
svendecabooterThanks for the great examples nfd!
I've added a link to them on the project page, for future reference to people struggling with regexes.
Comment #4
sahithi CreditAttribution: sahithi commentedCan anyone please tell me
how to validate a text field which can have numbers,alphabets,spaces and some special characters like , . ()_ -
using regular expression validator?
Thanks in advance
Comment #5
Liam MorlandMoved example to handbook.