Reputation: 5508
I am learning regex and I want to implement this in react app so when I write something on input field I want to allow user to write only numbers and maximum one space. This string also must starts with + character. My regex tool shows me good result but in app I cannot write anything.
const handlePhone = ({currentTarget}) => {
let val = currentTarget.value;
// Regular expression
const reg = /^\+\d+/g;
const isNumber = val.match(reg);
if (isNumber || val === '') {
setFieldValue('phone', val);
}
};
With this expression I wanted to implement this: starts with + and later you can write some digits.
But in app I cannot write anything. Why this tool is so different from this live matching?
With this:
const reg = /^\+\d+( \d+)*$/;
Upvotes: 5
Views: 3551
Reputation: 383
My Regex is pretty bloated but it should work.
const regex = \^\+[\d]+(\s)*(\d)+$\g;
Upvotes: 0
Reputation: 20737
This should work:
^\+?\d+( \d+)?$
^
- start anchor\+?
- optionally start with a plus sign\d+
- require at least one digit to follow( \d+)?
- Optionally allow a space which must be followed by one or more digits$
- end anchorhttps://regex101.com/r/pxbefb/1
Upvotes: 2
Reputation: 7949
Try out this regex , And also check the regex in this LINK
const reg = /^\+\d+ \d+$/gm;
^+ :- will check that string is starting with +.
\d+ :- this will allow 1 or more digits
\s :- This will allow only one space .
$ :- this will ensure that string ends with digit and this will restrict the second use of space character .
Upvotes: 0
Reputation: 147343
I think you need something really simple like /^\+\d* ?\d*$/
which means:
^\+
starts with '+'\d*
then zero or more digits?
(space?) then zero or one space\d*
then zero or more digits$
end of stringE.g.
function checkValue(el) {
let re = /^\+\d* ?\d*$/;
document.getElementById('err').textContent = re.test(el.value)? 'good':'bad';
}
<input oninput="checkValue(this)"><br>
<span id="err"></span>
Upvotes: 1