1

I've a textbox for name field where I've used asp validation for proper name format. I want to validate multiple spaces between the strings. How can I do that? The leading and trail spaces are removed by trim() function but how can I validate multiple spaces between the strings? like

multiple    spaces

no   space

My validation code::

<label>
    <span>Full name</span>
    <input type="text" id="txt_name" runat="server" required="required"/>      
    <asp:RegularExpressionValidator ID="rev_txt_name" runat="server" ControlToValidate="txt_name" ForeColor="Red" 
    ErrorMessage="Invalid name!" SetFocusOnError="True" ValidationExpression="^[a-zA-Z'.\s]{2,50}"></asp:RegularExpressionValidator>

</label>
5
  • 1
    Do you need to limit the whole string to 50 chars? You mean "one two three" is valid and "one<SPACE><SPACE>two<SPACE><SPACE>three" is not? Commented May 25, 2017 at 10:13
  • yes but character count is optional. Thank You! Commented May 25, 2017 at 10:14
  • 1
    Well, if it is optional, you may just use ^[a-zA-Z'.]+(?:\s[a-zA-Z'.]+)*$. If not, ^(?=.{2,50}$)[a-zA-Z'.]+(?:\s[a-zA-Z'.]+)*$. Commented May 25, 2017 at 10:15
  • Thank You! what if I've to validate it using character count also. Commented May 25, 2017 at 10:16
  • @WiktorStribiżew Please can you provide the answer so that I can mark it as correct reply for future reference. Thank You! Commented May 25, 2017 at 10:18

1 Answer 1

1

The pattern you are using allows matching whitespace anywhere inside the string and any occurrences, consecutive or not, since it is part of a rather generic character class. You need to use a grouping and quantify it accordingly:

^(?=.{2,50}$)[a-zA-Z'.]+(?:\s[a-zA-Z'.]+)*$

Note that the (?=.{2,50}$) lookahead requires the whole line to be of 2 to 50 chars long.

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{2,50}$) - a positive lookahead requiring any 2 to 50 chars other than a newline up to the end of the string
  • [a-zA-Z'.]+ - 1+ letters, single quote or dot chars
  • (?: - a non-capturing group start:
    • \s - 1 whitespace
    • [a-zA-Z'.]+ - 1+ letters, single quote or dot chars
  • )* - zero or more (*) occurrences
  • $ - end of string
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You for the nice explanation. Your description will be help others to understand regular expression in future also. Thank You!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.