Home > Net >  Regular expression to determine if phone number starts with a zero
Regular expression to determine if phone number starts with a zero

Time:03-17

How would I go about ensuring that numbers entered into a field starts with a 0? My initial question was suggesting that the company wants to force users to input 0 first, but I think an elegant solution would work better.

    function creationValidationNumber(dataValues, setErrors) {
     let testData:any = {};

     if ("numberPrime" in dataValues) testData.numberPrime = /^[a-zA-Z][0-9a-zA-Z 
     .,'-]*$/g.test(dataValues.numberPrime) ? "" : "Numbers must start with a 0";

     setErrors({ ...testData });

     return Object.values(testData).every((x) => x === "");
    }

I just don't know how to get the regular expression to test and throw an error if it doesn't start with 0

If anyone could please guide me on the right path.

CodePudding user response:

You don't need regex for this. Just check if the first character is "0":

dataValues.numberPrime[0] == "0"

CodePudding user response:

I don't know why you have a more complicated regex, all you need is:

/^0/
  • Related