Created
March 24, 2023 16:41
-
-
Save abcdeepakr/c7ee9dc163d23297068abbeb34e4a5c2 to your computer and use it in GitHub Desktop.
validate max input length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="form-options"> | |
<input id="pincode" type="number" | |
onkeypress="validateNumberFields(event)" pattern="\d*" | |
oninput="this.value=this.value.replace(/[^0-9]/g,'');" | |
type="number" | |
maxlength="6" /> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validateNumberFields(event) { | |
$(`#${event.target.id}`).on("keyup", function (e) { | |
var $field = $(this), | |
val = this.value, | |
$thisIndex = parseInt($field.data("idx"), 10); | |
if (this.validity.badInput || isNaN(val) || $field.is(":invalid")) { | |
// this.value = inputQuantity[$thisIndex]; | |
if (this.validity.badInput) { | |
this.value = inputQuantity[$thisIndex]; | |
} else { | |
this.value = "" | |
} | |
return; | |
} | |
if (val.length > Number($field.attr("maxlength"))) { | |
val = val.slice(0, event.target.maxLength); | |
$field.val(val); | |
} | |
// console.log(event.which) | |
inputQuantity[$thisIndex] = val; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment