I want to validate phone number like this
- 08xxxxxxxx
- 08xxxxxxxxxx
- 08xxxxxxxxxxxxx
first and second digit must be 08
and following with other digits minimum 10 digit and maximum 15 digit
I already tried this code
<form> <input type="tel" name="no_hp" class="form-control" pattern="[0]{1}[8]{1}[0-9]" maxlength="15" oninvalid="this.setCustomValidity('Nomor telepon harus di awali dengan 08 dan minimal 10')" required> <input type="submit"> </form>
in below video, I try to input 089
and it successes but try without minimum 10 digit
but in below video If I try to input wrong first number like 189
and then I update to right number same with first video 089
, its still says number is wrong.
so why after I correct format the number (leading by 08
), it still says number is wrong? how to fix that?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I think you can use the following regex as a pattern on the input field directly or use javascript
to do the same and show a warning message to the user.
JS Approach
const regex = new RegExp('^08[0-9]{8,13}$', 'gm');
if (regex.test('088884444714255')) {
console.log('valid number');
}else{
console.log('invalid number');
}
if (regex.test('0888844447142555')) {
console.log('valid number');
}else{
console.log('invalid number');
}
if (regex.test('078844447142555')) {
console.log('valid number');
}else{
console.log('invalid number');
}
HTML Pattern Approach
<form>
<input type="tel" name="no_hp" class="form-control" pattern="^08[0-9]{8,13}$" oninvalid=" this.setCustomValidity('Nomor telepon harus di awali dengan 08 dan minimal 10')" oninput="this.setCustomValidity('')" required>
<input type="submit">
</form>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0