Home > Back-end >  validate input using regex pattern
validate input using regex pattern

Time:11-05

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?

CodePudding user response:

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');
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related