Search code examples
regexxmlaem

Regex for string must not contain comma, semi comma, slash etc


I am working on a piece of regex, which a string must not contain characters * / : [ ] |

Here is my own try out but it does not really working

regex="/^[^*/:[]|]+/"

The purpose of this regex is actually for one of the Adobe CQ component I am developing. The requirement is if author type in any characters like * / : [ ] | in dialog textfield, give warning. The full dialog xml code showing as below:

<fieldConfig
        jcr:primaryType="cq:Widget"
        allowBlank="false"
        regex="/^[^*/:[]|]+/"
        regexText="Please enter a valid character"
        xtype="textfield"/>

I couldn't get the regex working properly.


Solution

  • It seems that all you need is to escape the [ and ] inside a character class add a $ (end of string) anchor:

    regex="/^[^*\/:\[\]|]+$/"
    

    If the regex can be passed as a string, then an equivalent is regex="^[^*/:\\[\\]|]+$".

    The end of string $ anchor makes sure that the whole string does not contain the characters inside the character class. It only checked if a substring at the beginning of the string contained no forbidden symbols.