IT社畜犬くわっちょのはてな

青森の片隅で働く、フルスタックエンジニアに憧れる器用貧乏なIT社畜犬の遠吠え

input type="number" 用のmaxlength指定処理を作ってみた。

こんな感じで

$('input[type="number"]').on('input', function () {
    var regex = new RegExp(/^[0-9]+$/);
    var regexDecimal = new RegExp(/^([1-9][0-9]*|0)(\.[0-9]+)?$/);
    if ($(this).val().length > $(this).attr('maxlength')) {
        $(this).val($(this).val().slice(0, $(this).attr('maxlength')));
    } else if (parseInt($(this).val(), 10) != 0 && !parseInt($(this).val(), 10)) {
        $(this).val('');
    } else if (parseInt($(this).val(), 10) < parseInt($(this).attr('min'), 10)) {
        $(this).val($(this).attr('min'));
    } else if (parseInt($(this).val(), 10) > parseInt($(this).attr('max'), 10)) {
        $(this).val($(this).attr('max'));
    } else if (typeof $(this).attr('decimal') === "undefined" && !regex.test($(this).val())){
        $(this).val(parseInt($(this).val(), 10));
    } else if (typeof $(this).attr('decimal') !== "undefined" && !regexDecimal.test($(this).val())){
        $(this).val(parseFloat($(this).val()));
    }
});

今のところいい感じには動いてる。