I want to handle phone number field in onChangeText
TextInput
React native
,
from this answer i can use ^08[0-9]{9,}$
pattern, but the problem is on first number, regex wont allow 0 because of 08
on regex pattern, and if i add 0|08...
, regex allow 0 but it's allow any number on 2nd number instead of 08.
My Question : what is the best way to force regex handle first number is 0 and second number is 8? so i get 08xxxxxxxxxx (when x is another number 0-9)
and here is an example of my current code in reactJS
, you can feel i can type any number after i'm typing 0, and for new suggested regex (^0|08[0-9]{9,}$)
i can't type any number anymore after 0,
Notes: i don't know why my question marked as duplicate since the duplicated not help me to fix my issue
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
let reg = /^0|08[0-9]{9,}$/
if(reg.test(event.target.value)){
this.setState({value: event.target.value});
}
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Phone:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>