如何使用javascript检查第一个数字是不是0 [英] how to check that the first number is not 0 using javascript

查看:327
本文介绍了如何使用javascript检查第一个数字是不是0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证文本框,以便没有人可以在文本框中输入字符。因为我的javascript代码是:

I want to validate a textbox such that no one can enter characters in textbox. for that my javascript code is :

function isSpaceKey(evt) {
          //   debugger;
            var charCode = (evt.which) ? evt.which : event.keyCode

            if ((charCode < 47 || charCode > 57) &&  charCode != 8) {
                alert("Enter Numeral Values only!");
                return false;
            }


            return true;
        }



它工作正常但我希望第一个数字不应该是0.我怎么能这样做?谢谢。


it is working fine but i want that the first number should not be 0. How can i do it? Thanks.

推荐答案

使用此代码



Use this Code

function vald1(objThis) {
            if (!(/^(?:[1-9]\d*|0)


/ .test(objThis。 value ))){
alert( 第一个数字不应为'0'。);
return false ;
}
else
return ;
}
/.test(objThis.value))) { alert("First number should not be '0'."); return false; } else return true; }


有很多方法可以做到这一点。



最简单的你的案例是检查文本框中文本的长度。对于长度= 0,即第一个字符,只是不允许0(密钥代码48)否则进行正常验证。因此,请将您的代码更改为:

There are many ways to do that.

Simplest in your case would be to check the length of the the text in the textbox. For length = 0 i.e first character, just don't allow 0 (key code 48) otherwise go with your normal validation. So change your code to:
function isSpaceKey(evt) {
    //   debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (document.getElementById("TextBoxID").value.length == 0) { //for first character
        if (charCode == 48) {
            alert("Enter Numeral Values only!");
            return false;
        }
    }
    else {
        if ((charCode < 47 || charCode > 57) && charCode != 8) {
            alert("Enter Numeral Values only!");
            return false;
        }
    }

    return true;
}





希望有所帮助!



编辑 - 我之前误解了这个问题。根据您的要求更新了答案。



Hope that helps!

Edit - I misread the question before. Updated the answer as per your requirement.


这篇关于如何使用javascript检查第一个数字是不是0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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