Exclude country code from "value" when phone input is optional and field is empty #166
Replies: 1 comment
-
If anyone is interested, here is the solution I came up with for an optional phone input with validation. I am using Add a dialCode state in your parent component Pass setDialCode as a prop to your react-international-phone component: In the onChange field of the react-international-phone component, add the following to control the dialCode state in the parent component:
Modify the example isPhoneValid function from the documentation to return true for empty phone string, dialCode, as well as initialized dialCode
Finally, in your handleSave function you can create a new form object with an empty phone string if the phone is equal to the dial code. This way, your database can store an empty string rather than the dial code
Hopefully someone finds this helpful! |
Beta Was this translation helpful? Give feedback.
-
After digging through the internet, I found react-international-phone to be the best React phone input component! Kudos! :)
I am using the phone input to generate E164 formatted phone strings with country code.
Does anyone have suggestions on how to generate an empty phone value without country code when the input field is optional and the input field is empty? (i.e. user hasn't inputted any value). That way an empty string is returned for the field instead of the country code for storage.
One workaround I have thought about is a simple if statement to detect if the value is less than 5 characters (including '+' character and max. 3-digit country code), and returning an empty string to be stored when this condition is satisfied. This method works but I'm wondering if the community has ideas on a more elegant solution.
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions