简体   繁体   English

输入文本字段,仅接受数字破折号

[英]Input text field that only accepts numbers dash numbers

I am trying to control input field using jQuery previously i had only numbers and could use $(this).autoNumeric() , now i have come around where it is required to change the input field in form of 'Numbers dash Numbers'. 我试图使用jQuery来控制输入字段,以前我只有数字,可以使用$(this).autoNumeric() ,现在我遇到了需要更改“数字破折号”形式的输入字段的问题。

I have tried few links from this site as well as others without any success, I am just beginner of UI, pls help me out. 我尝试了该站点以及其他站点的一些链接,但均未成功,我只是UI的初学者,请帮助我。

You will need to use a regular expression. 您将需要使用正则表达式。 I wouldn't rely solely on HTML5 input masks. 我不会仅仅依靠HTML5输入掩码。

/^\d+(-\d+)*$/

should suffice if there's no stronger constraints. 如果没有更严格的约束,就足够了。

$("#myfield").change(function(){ 
  var isValid = $(this).val().match(/^\d+(-\d+)*$/);
  if(!isValid){
    alert('only numbers and hyphesn please');
    return false;
 }
});

simple html: 简单的html:

<input id="myfield">

demo: http://jsbin.com/jeziqifebu/1/edit 演示: http : //jsbin.com/jeziqifebu/1/edit


UPDATE: 更新:

User wants numberstrings, ie 3.4.5 not just decimal figures. 用户需要数字字符串,即3.4.5不仅仅是十进制数字。

 $("#myfield").change(function(){ 
    var pattern = /^\d+(\.\d{1,2})?(\.\d{1,2})?(-\d+(\.\d{1,2})?(\.\d{1,2})?)?$/;
    var isValid = $(this).val().match(pattern);
    if(!isValid){
       alert('only numbers or valid range separated by hyphens please');
     return false;
   }
});

this will take 这将需要

2
2-3
2.3
2.3-4
2.3.4-5
2.3.4-5.6
2.3.4-5.6.7

Demo: http://jsbin.com/hivikudova/2/edit 演示: http//jsbin.com/hivikudova/2/edit

This solution doesnt allow you to enter anything but numbers and a single dash: JS FIDDLE 此解决方案不允许您输入数字和单破折号: JS FIDDLE

<input onkeypress="return isNumberKey(event);">

var dashCount = 0;
function isNumberKey(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 45) {
        dashCount++;
    }
    if ((charCode > 47 && charCode <58) || (charCode == 45 && dashCount < 2))
    {
        return true;
    }
  return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM