检查如果仅在输入中输入数值。 (jQuery的)

我想在jQuery的帮助下检查用户是否输入了正确的电话号码,到目前为止我已经到了这个阶段:

var phone = $("input#phone").val(); if (phone !== "") { //Check if phone is numeric $("label#phone_error").show(); //Show error $("input#phone").focus(); //Focus on field return false; } 

基本上它检查是否输入了电话号码,如果是,我想检查它是否是一个数字值,如果它没有显示错误消息。 任何人都可以帮助检查它是否是数字?

试试这个…它将确保字符串“phone”仅包含数字,并且至少包含一位数字

 if(phone.match(/^\d+$/)) { // your code here } 

jQuery中有一个内置函数来检查这个(isNumeric),所以请尝试以下方法:

 var phone = $("input#phone").val(); if (phone !== "" && !$.isNumeric(phone)) { //Check if phone is numeric $("label#phone_error").show(); //Show error $("input#phone").focus(); //Focus on field return false; } 

http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

检查出。 它应该是你正在寻找的。 用于jQuery的美国手机validation插件。

如果你想自己做,那么你将会有大量的工作。 查看isNaN()函数。 它告诉你它是不是一个数字。 您还需要了解正则表达式以进行validation。 如果您正在使用RegEx,那么您可以不使用isNaN() ,因为您无论如何都要进行测试。

我用过这个:

 jQuery.validator.addMethod("phoneUS", function(phone_number, element) { phone_number = phone_number.replace(/\s+/g, ""); return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, "Please specify a valid phone number"); 

我用它来检查所有文本框是否都有数值:

 if(!$.isNumeric($('input:text').val())) { alert("All the text boxes must have numeric values!"); return false; } 

或者一个:

 $.isNumeric($("txtBox").val()); 

适用于jQuery 1.7。

  if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){ alert('Please enter only numbers into amount textbox.') } else { alert('Right Number'); } 

我希望这段代码可以帮到你。

在此代码中,如果条件将返回true,如果存在任意数量的小数位数的任何合法十进制数。 并且警报将出现“正确号码”消息,否则它将显示警告弹出消息“请仅输入数量到文本框中”。

谢谢… :)

对于未来的访问者,你可以添加这个function,允许用户只输入数字:你只需要添加jquery和类名到输入检查到http://jsfiddle.net/celia/dvnL9has/2/

 $('.phone_number').keypress(function(event){ var numero= String.fromCharCode(event.keyCode); var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9]; index = myArray.indexOf(numero);// 1 var longeur= $('.phone_number').val().length; if(window.getSelection){ text = window.getSelection().toString(); } if(index>=0&text.length>0){ }else if(index>=0&longeur<10){ }else {return false;} }); 

我使用了这种validation….检查粘贴的文本,如果它包含字母,则为用户显示错误,然后在延迟后清除该框,以便用户检查文本并进行适当的更改。

 $('#txtbox').on('paste', function (e) { var $this = $(this); setTimeout(function (e) { if (($this.val()).match(/[^0-9]/g)) { $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow"); setTimeout(function (e) { $this.val(null); },2500); } }, 5); }); 

这不是问题的准确答案,但电话validation的另一个选项是确保以您期望的格式输入数字。

这是我已经处理过的一个函数,当设置为onInput事件时,将剥离任何非数字输入,并在“右”点自动插入破折号,假设xxx-xxx-xxxx是所需的输出。

 function formatPhone(e) { var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/); e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : ''); }