如何使用javascript检查第一个数字是不是0

编程入门 行业动态 更新时间:2024-10-23 12:24:43
本文介绍了如何使用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

本文发布于:2023-10-27 18:53:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   数字   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!