首页 文章

如何使用正则表达式检查字符串是否是一个不以0开头的正整数?

提问于
浏览
-1

经过大量研究后,我还没有发现满足所有这些IF条件的正则表达式 . 代码效果很好,但我认为可以使用RegEx简化 .

目标:在1到9之间的正整数上返回true,而不是从零开始 . 为每个其他值返回false .

看一看 .

// Validation functions


function hasPeriod(s) {
  // Return true or false.
  // True if a period is entered at any point in time.
  return s.indexOf('.') > -1;
}
// See more... http://2ality.com/2014/05/is-integer.html
function isInteger(s) {
  // Return true or false.
  // True if the remainder of dividing it by 1 is 0.
  return s % 1 === 0;
}



// Bind keyup event to prep_work_item_input.
$('#input1').on('keyup', function (e) {

  // TRIM text input value on declaration...
  // May contain spaces...
  var input_value = $(this).val().trim();

  // Refresh text input after Trim!
  // Does not contain spaces
  $(this).val(input_value);

  // If text input is EMPTY after Trim...
  if (input_value.length == 0) {

    // Stop at this if and dont proceed.
    return false;

  } 

  // If a PERIOD is typed into text input at any point in time...
  if (hasPeriod(input_value)) {

    // Clear input
    $(this).val('');

    // Stop at this if and dont proceed.
    return false;

  }

  // If text input value is NOT an INTEGER...
  if (!isInteger(input_value)) {

    // Clear input
    $(this).val('');

    // Stop at this if and dont proceed.
    return false;
  }

  // If text input value IS an INTEGER but EQUAL to 0...
  if (input_value == 0) {

    // Clear input
    $(this).val('');

    // Stop at this if and dont proceed.
    return false;
  }

  // If text input value IS an INTEGER and also GREATER than 0...
  if (input_value > 0) {

    // If we have made this far... 
    // we probably have a real integer that is not zero.

    // We can finally begin to calculate

    input_value = parseInt(input_value);

    // random cost multiplier for this example
    var cost = parseFloat('0.78');

    // calculate subtotal...
    cost = input_value * cost;

    // Set prep_work_item_subtotal...        
    console.log(input_value + ' ' + 'SF' + ' / ' + ' $' + cost.toFixed(2));

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Enter value below:</label>
<br>
<input type="text" id="input1" placeholder="enter value">

2 回答

  • 2

    正则表达式不是你想要做的解决方案 .

    您应该做的是根据 if 语句确切的失败向用户提供有意义的错误消息 .

    例如,如果您的输入需要 . 但没有,则可以告诉用户您想要的确切内容 . 但是,如果你只有一个大型的超级正则表达式,你绝对无法知道导致它失败的原因 .

    考虑一下这个小小的UX课程!


    或者只使用正确的输入类型 .

    <input type="number" min="0.01" step="0.01" />
    
  • 2

    从阅读代码看,您需要检查数字是否大于0 .
    你可以用这个正则表达式做到这一点:

    ^[1-9]\d*$
    

    它会检查输入:

    • 以数字开头但不是0
    • 包含任意数量的数字
    • 以数字结尾

相关问题