1

I have a form field in which I want to allow 1 to 50 letters, numbers, and spaces in it. Just not start with a space and ends with a space. (Or, alternatively, if it starts with a space, it's not counted toward 50.)

I have something like:

^[^s][a-zA-Z0-9_ ]{1,50}[^s]$

But something like "AB" now doesn't pass, because nothing match the {1,50}.

EDIT:

The regex is for the HTML input element pattern field.

4
  • 1
    ´[^s]` means match anything but s - guess you want anything but \s (whitespace). And that you can do with \S (capital S) - ^\S[a-zA-Z0-9_ ]{1,50}\S$. Commented Mar 16, 2016 at 9:32
  • And more to the point - I guess you're looking for more like ^\s*[a-zA-Z0-9_ ]{1,50}\s*$ which allows white space in the beginning and at the end, without them being included in the 50. (The logic of) Your regex requires white space in the beginning and the end. Commented Mar 16, 2016 at 9:35
  • ^[^\s][a-zA-Z0-9_ ]{1,50}\b$ or ^\b[\w ]{1,50}\b$ regex101.com/r/lE5hS9/1 Commented Mar 16, 2016 at 9:35
  • @ClasG Your description sounds about right. :) Commented Mar 16, 2016 at 9:38

3 Answers 3

2

Try this

^\b[\w ]{1,50}\b$

Demo

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

1 Comment

This works. Though it doesn't permit space before and after. It's more stringent, but it works for me. Thanks.
1

Or with minimal use of regex:

function myFunction() {
    var input = document.getElementById('myInput').value.trim();

    if (input.length < 1 || input.length > 50) {
        document.body.innerHTML += "wrong lenth";
        return false;
    }

    var re = /^[\w ]+$/;

    if (re.exec(input) !== null) {
        document.body.innerHTML += input + " is valid";
        return true;
    } else {
        document.body.innerHTML += input + " is not valid";
        return false;
    }
}
<input id="myInput">
<button onclick="myFunction()">Test</button>

1 Comment

Thanks for the input. Though I need it to be in the pattern field. (HTML 5 Constraint Validation API) Sorry about wasn't being clear.
1

My comment as an answer ;)

^\s*[a-zA-Z0-9_ ]{1,50}\s*$

This regex will allow entry of white space in the beginning and at the end without requiring it as your attempt (kind of) did.

Regards

Edit:

Combine Tims answer with this and you avoid space only:

^\s*\b[\w ]{1,50}$\s*

This forces the string to have a word boundary - i.e. must contain a word character.

2 Comments

I tried it. Unfortunately, that makes one space by itself pass the test as well (within pattern attribute of an input element), which should not be allowed.
Actually you could combine Tims answer with mine and get exactly what you're looking for. See edit.

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.