输入框-防止用户输入0作为第一位数字 [英] Input box - Prevent user from entering 0 as first digit

查看:446
本文介绍了输入框-防止用户输入0作为第一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个输入框.我希望该用户不能输入以0开头的任何数字.请注意,开头只能是0.它可以在结尾或中间,但不能在开头.

I have 2 input boxes. I want that user should not be able to enter any digit which starts with 0. Note that only 0 at the beginning. It can be at the end or middle but not at the beginning.

所以允许4、40、4440,但不允许04.

So allow 4, 40, 4440 but not 04.

检查此小提琴,其中我还提出了其他一些限制,例如仅允许数字值,长度是4.现在我想添加与0相关的限制.

Check this fiddle where I've put several other restrictions like only numeric values are allowed, length is 4. Now I want to add the restriction related to 0.

如何使用jQuery完成此操作?

How can this be done using jQuery?

HTML

<input name="major" size="1" value="4" class="major_rev">.

<input name="minor" size="1" value="24" class="minor_rev">

推荐答案

Sangram miklshake 的回答对我有所帮助.下面是组合的解决方案.

Sangram and miklshake's answers helped me. Below is the combined solution.

$(document).on('keyup','.major_rev', function(event){

    var input = event.currentTarget.value;

    if(input.search(/^0/) != -1){
         alert("you have started with a 0");   
    }
});
$(document).ready(function() {
    //For numeric
    $(".major_rev").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8) {
            // let it happen, don't do anything

        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode !==9) && (event.keyCode < 48 || event.keyCode > 57 )) {
                event.preventDefault(); 
            }   
                else{

              if($.trim($(this).val()) =='')
            {
                if(event.keyCode == 48){
                event.preventDefault(); 
                }
            }

            }
        }
    });
    $(".minor_rev").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
            if($.trim($(this).val()).length==0)
            {
                if(event.keyCode==48){
                event.preventDefault(); 
                }
            }
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
            else{

              if($.trim($(this).val()) =='')
            {
                if(event.keyCode == 48){
                event.preventDefault(); 
                }
            }
            }
        }
    });
    //For MaxLength
    $(".major_rev").prop("maxlength","4");
    $(".minor_rev").prop("maxlength","4");
});

jsFiddle

这篇关于输入框-防止用户输入0作为第一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆