1

I have a job title field in a form, where I want it to allow a response which contains only letters and numbers, where at least one letter is required and any numbers are optional. I am using the following pattern in my input tag:

pattern="\w*[a-zA-Z]\w*"

This pattern checks out on the RegEx testers I have tried to use, yet when I provide an answer on my form of "Manager 2" it will not let me continue. Is there something different about how browsers interpret

3
  • Show us an example input where it fails... Commented May 22, 2019 at 20:16
  • What does it fail with? If you plan to also support whitespaces, try pattern="[0-9\s]*[a-zA-Z][a-zA-Z0-9\s]*". Commented May 22, 2019 at 20:16
  • Manager 2 contains a space and then 2 but your pattern requires at least 2 chars. Try \w*[a-zA-Z]\w*(?: \w+)* Commented May 22, 2019 at 20:18

2 Answers 2

2

If you use the pattern attribute on a form, the ^ and $ are implied so it will match the whole value. Your pattern \w*[a-zA-Z]\w* matches at least a single char a-z but not a space.

If you want to match Manager 2 you could use your pattern followed by a group which repeats 0+ times matching a space and 1+ word characters.

\w*[a-zA-Z]\w*(?: \w+)*

See a regex demo

Note that \w also matches an underscore.

A bit broader pattern to allow multiple spaces, and also at the end:

^\w*[a-zA-Z][ \w]*

Regex demo

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

Comments

0

Your original expression is just fine and missing space. Here, we can start with a simple pattern, maybe something similar to:

[A-Za-z\s0-9]+

If it was necessary, we could add capturing group around it to save our data in $1:

([A-Za-z\s0-9]+)

enter image description here

RegEx

If this expression wasn't desired, it can be modified or changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Demo

const regex = /([A-Za-z\s0-9]+)/gm;
const str = `Manager 2`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

DOMO

Comments

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.