简体   繁体   中英

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'.

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.

You will need to use a regular expression. I wouldn't rely solely on HTML5 input masks.

/^\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:

<input id="myfield">

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


UPDATE:

User wants numberstrings, ie 3.4.5 not just decimal figures.

 $("#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

This solution doesnt allow you to enter anything but numbers and a single dash: 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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