Javascript Validator for Input Number

This javascript will validate/allow the number only when event key is pressed. For example result of it:

tutorial above, when you can not directly add the attribute inside html tag. but if you can add it, you can following this tutorial bellow:

<input id="id_price" type="number" min=0 onkeypress="return isNumber(event)"/>
<script type="text/javascript">
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
</script>

Refference: http://stackoverflow.com/a/7295864

hope it usefull.

AM

Written by Agus Makmun Author

SDE Lead working across the whole stack: backend, frontend, databases and the infrastructure that ships them. These days mostly infrastructure and Next.js, like moving apps off Vercel and Supabase to self-hosted.

arrow_backPrevious post Setup Django in apache2 Raspberry Pi
search esc