I am using http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ for validation. Validation rules are defined in a following way:
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Only letters"
}
I would like to add new rule, which will exclude one single word. I have read some similar questions on StackOverflow and tried to declare it with something like this
"regex": /(?!exclude_word)\^[a-zA-Z\ \']+$/,
But it didn't work. Can you give me some advices how to do it?
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
This is a good time to use word boundary assertions, like @FailedDev indicated, but care needs to be exercised to avoid rejecting certain not-TOO-special cases, such as wordy
, wordsmith
or even not so obviously cases like sword
or foreword
I believe this will work pretty well:
\b(?!\bword\b)\w+\b
This is the expression broken down:
\b # assert at a word boundary
(?! # look ahead and assert that what follows IS NOT...
\b # a word boundary
word # followed by the exact characters `word`
\b # followed by a word boundary
) # end look-ahead assertion
\w+ # match one or more word characters: `[a-zA-Z0-9_]`
\b # then a word boundary
The expression in the original question, however, matches more than word characters. [a-zA-Z\ \']+
matches spaces (to support multiple words in the input) and single quotes as well (for apostrophes?). If you need to allow words with apostrophes in them then use the following expression:
\b(?!\bword\b)[a-zA-Z']+\b
\b(?:(?!word)\w)+\b
Will not match the "word".
It's unclear from your question what you want, but I've interpreted it as "not matching input that contains a particular word". The regex for this is:
^(?!.*\bexclude_word\b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With