Reputation: 1276
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
Upvotes: 1
Views: 124
Reputation: 27723
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]+)
If this expression wasn't desired, it can be modified or changed in regex101.com.
jex.im visualizes regular expressions:
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}`);
});
}
Upvotes: 0
Reputation: 163217
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]*
Upvotes: 2