Skip to content

Instantly share code, notes, and snippets.

@Shahzad6077
Created January 18, 2022 05:58
Show Gist options
  • Save Shahzad6077/3a035d8d04cba4aef2f6098ee26df22b to your computer and use it in GitHub Desktop.
Save Shahzad6077/3a035d8d04cba4aef2f6098ee26df22b to your computer and use it in GitHub Desktop.
US Phone Validation using regex Reactjs
import { useState } from "react"
export default function Index(){
const [phone,setPhone] = useState("");
const formatPhoneValidation = (current) => {
const value = `${current.value}`;
const input = value.replace(/\D/g, "").substring(0, 10); // First ten digits of input only
const areaCode = input.substring(0, 3);
const middle = input.substring(3, 6);
const last = input.substring(6, 10);
if (input.length > 6) {
setPhone(`(${areaCode}) ${middle} - ${last}`);
} else if (input.length > 3) {
setPhone((p) => (`(${areaCode}) ${middle}`);
} else if (input.length > 0) {
const updatedVal = `(${areaCode})`;
setPhone(updatedVal);
const strLength = updatedVal.length;
if (phoneRef.current.setSelectionRange !== undefined) {
const end = strLength > 0 ? strLength - 1 : strLength;
phoneRef.current.setSelectionRange(strLength, end);
}
} else {
setPhone("");
}
};
const onPhoneFieldClick = (e) => {
const elem = e.currentTarget;
const input = elem.value.replace(/\D/g, "").substring(0, 10);
if (input.length > 3) {
return null;
}
setTimeout(
(function (el) {
const strLength = el.value.length;
return function () {
if (el.setSelectionRange !== undefined) {
const end = strLength > 0 ? strLength - 1 : strLength;
el.setSelectionRange(strLength, end);
}
};
})(elem),
5
);
};
return(
<input type="text" value={phone} onChange={formatPhoneValidation} onClick={onPhoneFieldClick} placeholder="(123) 456 7890" />
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment