Help to improve this javascript input mask

安稳与你 提交于 2019-12-24 11:35:23

问题


Features

  • Only numbers
  • A unique dot (.)

But...i need improve to allow user digits only two numbers after the dot

Valid examples:

  • 121213
  • 123450.10
  • 12345678910111213.39

The current code (adapted from this, not need to keep exactly the same code...) :

<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt,obj){

         var containsDot = obj.value.indexOf(".");

         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57)){
              if(charCode == 46 && containsDot < 0){
                return true;
              }
                return false;
         }
         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event,this)" type="text" name="txtChar">
   </BODY>
</HTML>

回答1:


I've posted a fully working version of this here: http://jsfiddle.net/georgecalm/NRtVs/2/

HTML:

<input id="txt" type="text" name="txtChar" />

JS:

var isStrValid = function(str) {
  return ((str.match(/[^\d^.]/) === null) 
       && (str.replace(/\d+\.?\d?\d?/, "") === ""));
};

var node = dojo.byId("txt");
dojo.connect(node, "onkeyup", function() {
    if (!isStrValid(node.value)) {
      node.value = node.value.substring(0, node.value.length-1);
    }
});

The first checks (of the isStrValid) makes sure you don't have anything but numbers and a dot. The second checks the pattern.




回答2:


Just use a regular expression. E.g.

function isNumberKey(evt, obj){
    return obj.value.match(/[0-9]*(\.[0-9]{0,2})?/)
}



回答3:


If it has a dot, but does not have two digits after it, return false.

if(containsDot && obj.value.split(".")[1].length != 2){
  return false; 
}



回答4:


You can start off the function with

if (obj.value.match(/\.[0-9][0-9]/)) {
    // Already has two decimals
    return false;
}


来源:https://stackoverflow.com/questions/5120602/help-to-improve-this-javascript-input-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!