2

I'm trying to create a Regex test in JavaScript that will test a string to contain any of these characters:

 a...z A..Z 0..9 and  & - . '

I have do this but not match:

^[a-zA-Z0-9&.-]

Complete Code:

    <field-validator type="regex">
        <param name="expression">^[a-zA-Z0-9&.-]+$</param>
        <param name="caseSensitive">false</param>
        <message key="format.name" />
    </field-validator>
Roman C
  • 49,761
  • 33
  • 66
  • 176
Mercer
  • 9,736
  • 30
  • 105
  • 170

4 Answers4

3

this appears to work:

[\&\-\.']

adding in the letters and numbers:

[a-zA-Z0-9\&\-\.']

(Updated after comment)

Greg
  • 125
  • 8
2

You are using the regex inside XML file, so best way is to use a CDATA block in order to use literal & and ' symbols inside it. Either of the two will work:

<param name="regex"><![CDATA[[a-zA-Z0-9'&.-]]]></param>

or (if a full string match is required):

<param name="regex"><![CDATA[(?s).*[a-zA-Z0-9'&.-].*]]></param>

Since you are using <param name="caseSensitive">false</param>, you may even omit the A-Z or a-z in the pattern.

Note that (?s) enables the DOTALL mode so that a . could match any character including a newline.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You have to \ escape special characters.

[a-z0-9\-&\.']
Community
  • 1
  • 1
Alex
  • 9,911
  • 5
  • 33
  • 52
0

If you want to test of the input contains anywhere one of these characters, remove the leading ^ of the regex. That says that any of these characters has to be the first character.

Also, your regex does not include the character '.

Martin Nyolt
  • 4,463
  • 3
  • 28
  • 36