nitin nitin - 1 year ago 64
Javascript Question

In a RegEx I need to allow spaces only in middle and prevent spaces at beginning and end

I have a requirement wherein I have below requiements to validate a name field:

  1. don't allow following symbols:

  2. can´t contain numbers

  3. can´t contain blank spaces at the begining or at the end

I have used below regex:


It is fulfilling all the conditions except that is is also restricting spaces in between the string. For ex:

It restricts format: "firstname lastname"

I need the above format to be allowed. I only need to restrict spaces at beginning and end.

Answer Source

I assume it is used in some kind of a RegularExpressionAttribute validation, and you just want to use a single pattern for this.

You have already the first building block:


This matches any char but the ones defined in the set. It does not match whitespace. If you quantify with * and wrap with anchors, no whitespace will be allowed anywhere in the string. So, you just need to add an optional group (quantified with * or ? or {x,y} depending on how many spaces you want to allow):

                                        ^^^                                         ^^

If you want to also match an empty string, wrap the pattern with an optional non-capturing group:

 ^^^                                                                                     ^^

Escape backslashes as needed.

As for the hyphen in the names: it might be appropriate to allow it in the same place as whitespace:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download