I'm working with a regular expression pattern that validates for a three-digit number.
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("123.") // false
My goal is to implement this regex as an input restriction on a textbox.
Essentially, I want to allow the character to be typed only if it matches the regex, otherwise prevent it.
The issue arises because no value will ever fully match; for example, typing "1" would not meet the criteria.
Is there a way to test for a partial match using a regex in JavaScript?
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("12") // "partial match"
/^\d{3}$/.test("a12") // false
EDIT
\d{3} was just an example. I actually need to use an email regex or phone regex as input restrictions.
"email" // true
"email@" // true
"email@@" // false
"@yahoo.com" // false
EDIT 2
I have created a textBox plugin with input restrictions based on a regular expression.
The regex can vary, for instance a hex color Regex: (#){1}([a-fA-F0-9]){6}
I want to disallow users from inserting characters that do not match the regex.
For example, when the textbox is empty, "#" should be the first allowed character.
However, testing "#" against the regex returns "false" as "#" alone is not valid.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // false
But "#" is considered partially valid as it follows the regex format (and should be allowed).
I am seeking a way to verify if a string is a partial match of a regex so that I can permit the user to type the character.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#0") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#00") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#000") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#0000") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#00000") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000") // partial match, allow typing
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000D") // not a match, prevent typing