how can I prevent a user to type 0 as the first character in a text input using vanilla javascript? [closed]

I have this html block:

<div class="form-group flex-auto" >
                <input maxlength="2" class="form-control format__itemForm" type="text" ng-model="$ctrl.codigoPaisTelefono"   prevent-keys="{{ $ctrl.caracteresExcluidos }}"
                required oninput="this.value== 0? this.value == '' :void(0)"
                > 
            </div>

I need to prevent users to type 0 as the first character, I tried oninput method above, but didn’t work.

Any clue?

Answer

Something like this maybe?

function validate(element){
  var val = element.value;
  if(val.charAt(0)=='0'){
    element.value=val.substring(1, val.length);
  }
}
<input oninput="validate(this)">

Leave a Reply

Your email address will not be published. Required fields are marked *