1

I want to validate a text box that should not have

  1. Spaces in the beginning
  2. All spaces
  3. Spaces in the end

Here is the textbox code:

<input type="text" id="username" name="username" placeholder="Username..." required="required">

I can't use trim because of the implementation of the code is a bit complex, It would break other functionality. This is only a carry over project to me. So I decided to filter it out on the HTML textbox it self. But I don't know how to do this.

Update:

By the way I'm asking for a regex pattern.

3
  • Like this: jsfiddle.net/njUSJ ? Commented Oct 14, 2013 at 3:00
  • @Passerby That would do it. Commented Oct 14, 2013 at 3:01
  • If you enter only one character, it is invalid Commented Oct 14, 2013 at 3:05

1 Answer 1

3
^\S(?:[\s\S]*\S)?$

should do it.

Translated into English, it's

^\S - starts with a non-space character

(?:...)?$ - optionally followed by ... which continues to the end of input

[\s\S]*\S - any number of any character, followed by a non-space character

Sign up to request clarification or add additional context in comments.

9 Comments

Isn't [\s\S] the same as .?
@Havenard . will does not include a new-line - [\s\S] does.
Afaik \s matches newlines too. At least with the /s flag, but I guess it depends on the implementation.
@Havenard, no . and [\s\S] are not the same. HTML5 specifies regexs in terms of the EcmaScript spec, which defines . as "Atom :: . evaluates as follows: 1. Let A be the set of all characters except LineTerminator".
@Havenard, there is no /s flag in EcmaScript which is the controlling spec per HTML5 which says "The pattern attribute ... If specified, the attribute's value must match the JavaScript Pattern production."
|

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.