Javascript文本字段验证||钱投入

时间:2016-01-07 01:54:26

标签: javascript validation jsp

我目前有这个验证,但是当多次按下输入时,输入有时会通过。

文本字段ID:service-rate-amount

$('#service-rate-amount').keyup(function() {
               var val = $(this).val();
               var checkIf50or00cents = new RegExp("^[0-9]+(\.([0,5]{1})?([0]{1})?)?$");
               var limitDigits = new RegExp("/^\d{0,3}(\.\d{1,2})?$/");

               if(isNaN(val) && val != "."){
                   showMessageModal("Only numeric characters are accepted");
                    val = val.replace(/[^0-9\.]/g,'');
                    if(val.split('.').length>2) {
                        val = val.replace(/\.+$/,"");
                   showMessageModal("Only one decimal point is accepted");
                    }
               } else if (!checkIf50or00cents.test(val)){
                   val = val.slice(0,-1);
                   showMessageModal("Only 50 cents or 00 cents are allowed");
               }          


               if (!(/^\d{0,3}(\.\d{1,2})?$/.test(val))) {
                   if(val.length == 4){
                       if( val.charAt(3) != "."){
                           val = val.slice(0, -1);
                           showMessageModal("Only three digits before decimal point is accepted");
                       }
                   }
               }

               $(this).val(val); 
            });

我想要一个可以接受的输入字段.... 00.50至999.50

我需要增加0.50分,对不起我的英文不好

2 个答案:

答案 0 :(得分:1)

如果将值解析为可以比较的数字,则可以消除一些复杂性。见下面的评论



var dollars = document.querySelector('#dollars');

function checkDollarInput(){
  
  var value     = parseFloat( dollars.value ),
      valueInt  = parseInt( value );
  
  if( dollars.value.match(/[^0-9.-]/) ){
    showMessageModal('please use only numbers', value);
    return false;
  }
  
  // check the max value
  if( value > 999.5 ){
    showMessageModal('over max value', value);
    return false;
  }
  
  // check the min value
  if( value < 0.5 ){
     showMessageModal('under min value', value);
    return false;
  }
  
  // ensure the correct decimal using modulo division remainer
  if( value % valueInt !== 0 && value % valueInt !== .5 ){
    showMessageModal('needs to be .0 or .50', value );
    return false;
  }
  
  console.log( 'success', value );
  
  // all tests have passed
  return true;
}

// im only logging value for the sake of testing
function showMessageModal( message, value ){
  console.log.apply(console, arguments);
  // do something to show the modal
}
&#13;
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
I want to have a input field that will accept .... 00.50 up to 999.50
<form id="form">
  <input id="dollars" type="text" value="40.50" />
  <input id="submit" type="button" value="checkDollarInput" onclick="checkDollarInput()" />
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用类型为input的{​​{1}}过滤所有文字输入。

HTML

number

的JavaScript

<input id="validate" type="number">