I'm trying to create a textinput
that only accepts numeric characters and the first character must be 3 in React Native.
const [inputs, setInputs] = React.useState({
num: '',
});
let numOnly = /^[0-9\b] $/;
let valid = true;
if (!inputs.num.trim() || inputs.num.length < 10 || !inputs.num.match(numOnly)) {//if number field is not in correct format
handleError('Please input phone number correctly', 'phone');
valid = false;
}
CodePudding user response:
Use this regex : /^3\d{9}$/
Description:
^
assert position at start of the line3
first character must be 3.\d{9}
9 characters after the first one has to be digits$
assert position at the end of a line
As you specified the first character, the 9 next ones and start/end of the line, the total length has to be 10.
You can replace $
by \Z
for end of the string instead of end of the line
CodePudding user response:
You can use below Regx to validate phone number:-
const reg = /^[0]?[3]\d{9}$/;
if (reg.test(phone) === true) {
if (phone.length > 9) {
console.log("valid phone number");
} else {
console.log("Invalid phone number");
}
}
You can put the numbers in this array [3] like [3789] that you want to the phone number starts with.