1

I want to validate phone number like this

  1. 08xxxxxxxx
  2. 08xxxxxxxxxx
  3. 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

enter image description here

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.

enter image description here

so why after I correct format the number (leading by 08), it still says number is wrong? how to fix that?

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

6 Comments

is it possible if only use html without javascript?
@E-Place I've updated my answer, to show you both js & html approaches.
I tried in my program and I run code snippet from your code, it's same error. please see the video gifyu.com/image/e5uJ
Woops! I limited it to [0-8] previously. it should have been [0-9]. Corrected now.
ooh it's work. but if I try custom message using oninvalid="this.setCustomValidity('Nomor telepon harus di awali dengan 08 dan minimal 10')" , it's always false when after I corrected the number. like second video in my question. or have other way to custom message?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.