How to do so that my field must at least be able to contain only numbers and a + in front of the number (if the user wishes)

69 Views Asked by At

For example the user can enter: +444123454656656 OR 123454656656 - only numbers or a + in front of the number.

<TextFieldFormsy
    className="myclasse"
    variant="outlined"
    label={t("phone_number")}
    id="phone_number"
    name="phone_number"
    value={phone_number}
    onChange={handleChange}
/>
1

There are 1 best solutions below

3
Domino987 On

You can simply filter the input in onChange to remove everyting you do not want:

const isValidChar = (char, index) => {
    if(index === 0 && char === "+") {
        return true;
    } 
    return !isNaN(char);
}

const filteredInput = input.split("").filter((char, index) => isValidChar(char, index)).join("")

here is a fiddle for the filter.