I am trying to control a text input field in a react application by only allowing an empty string, digits or an optional plus character at the start.
The regex pattern I am using is the following:
export const phoneNumberTestPattern = new RegExp('^\+?\d+?$');
This pattern is used to test the inputs value whenever the input is changed
onChange={ (e) => {
if (e.target.value === '' || phoneNumberTestPattern.test(e.target.value)) {
field.onChange(e.target.value);
}
}}
The pattern is working correctly for allowing only digits. But the optional plus character at the start is not being matched when the onChange event parameter returns a +
value as e.target.value
.
The event.target.value
does return the +
as a value when typed in, but the test pattern does not recognize it as something that matches so the field.onChange
method is never fired.
I dont understand what the reason for this is, and why the pattern is not matching a plus character at the start of the string being sent to it. Could it be possible the value I am sending to the test pattern is a string and I am trying to match it against a plus operator ?
Any help would be greatly appreciated.