Home > Net >  Combination of two JS codes
Combination of two JS codes

Time:01-04

I want to validate a Polish zip code field which should be in 11-111 format

I have a little problem with combining two JS codes.

One of the codes is responsible for entering only numbers in the field

this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')

This code is for inserting a "-" after the second number.

if(this.value.length==2 && this.value.indexOf('-')==-1) this.value ='-';

I want to add the code in "oninput".

<input inputmode="numeric" oninput=""/>

Unfortunately, I'm having trouble combining both codes. Can anyone help me?

CodePudding user response:

This will allow numbers and hyphens and add a hyphen in the 3rd position

You can add to it if you want to make sure the hyphen is the 3rd character and there are only 7 characters

Your example was testing decimal points etc

document.getElementById("zip").addEventListener("input", function() {
  let val = this.value;
  if (val.length == 2 && val.indexOf('-') !== 2) val  = '-';
  val = val.replace(/[^0-9-]/g, '');
  this.value = val;
})
<input inputmode="numeric" id="zip">

  • Related