'Regex for adding a dial code to a phone number
Hey I am beginner with regexs and I am not able to figure this out. What is the regular expression that adds the dial code (420) to phone number("tel" state variable here) if missing/adds plus character if missing/if there are 12 numbers already, turn the three first into dial code. Here are the desired outputs:
123456789 --> +420 123 456 789
(+420) 12 34567 89 --> +420 123 456 789
+420-123456789 --> +420 123 456 789
+987123456789 --> +987 123 456 789
420123456789 --> +420 123 456 789
import React, { useContext, useState, useEffect } from "react";
import DataContext from "../store/data-context";
function Form() {
const [name, setName] = useState("");
const [secName, setSecName] = useState("");
const [tel, setTel] = useState("");
const [note, setNote] = useState("");
const [state, setState] = useState({
name: "",
secName: "",
tel: "",
note: "",
});
const { dispatchDataState } = useContext(DataContext);
const handleSubmit = (e) => {
e.preventDefault();
console.log(name);
const payload={...state, tel: state.tel.replace(/[^+\d]+/g, "").split('').reverse().join('').replace(/([0-9]{3})/g, "$1 ").split('').reverse().join('')}
console.log(state)
console.log(tel)
dispatchDataState({ type: "ADD_DATA", payload:payload});
setState(
{
name: "",
secName: "",
tel: "",
note: "",
}
)
console.log(state);
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Jméno
<input
type="text"
required
value={state.name}
onChange={(e) => setState({ ... state, name: e.target.value })}
/>
</label>
<label>
Příjmení
<input
type="text"
required
value={state.secName}
onChange={(e) => setState({ ... state, secName: e.target.value })}
/>
</label>
<label>
Telefonní číslo
<input
type="text"
required
value={state.tel}
onChange={(e) => setState({ ... state, tel: e.target.value })}
/>
</label>
<label>
Poznámka
<input
type="text"
value={state.note}
onChange={(e) => setState({ ... state, note: e.target.value })}
/>
</label>
<input type="submit" value="Odeslat" />
</form>
</div>
);
}
export default Form;
Solution 1:[1]
You can use intl-tel-input package for this feature instead of implementing logic by yourself.
It's a popular zero-dependency package that has:
- dial code prefix for each country
- flag image for each country
- optional validation for user inputs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NeNaD |