Freestyle09
Freestyle09

Reputation: 5508

Number formatting using regex with special characters

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.

enter image description here

But in app I cannot write anything. Why this tool is so different from this live matching?

With this:

const reg = /^\+\d+( \d+)*$/;

enter image description here

Upvotes: 5

Views: 3551

Answers (4)

Anthony Gedeon
Anthony Gedeon

Reputation: 383

My Regex is pretty bloated but it should work.

const regex = \^\+[\d]+(\s)*(\d)+$\g;
  1. ^+ just negates the power of +
  2. [\d]+ is letting you pick 0-9 digits 1 or more times
  3. (\s)* is a group and it allows for 0 or 1 space
  4. (\d)+$ can pick digits between 0-9 one or more time. And $ is just the end anchor

Upvotes: 0

MonkeyZeus
MonkeyZeus

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 anchor

https://regex101.com/r/pxbefb/1

Upvotes: 2

Pushprajsinh Chudasama
Pushprajsinh Chudasama

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

RobG
RobG

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 string

E.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

Related Questions