javascript - 如何使用正则表达式检查字符串是否为不以 0 开头的正整数?
问题描述
经过大量研究,我还没有发现满足所有这些 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">
解决方案
正则表达式不是您尝试做的事情的解决方案。
相反,您应该做的是根据确切的if
语句失败向用户提供有意义的错误消息。
例如,如果您的输入需要 a.
但没有,那么您可以准确地告诉用户您想从他们那里得到什么。但如果你只有一个大的 über-regex,你绝对无法知道是什么导致它失败。
考虑一下这是一个小小的 UX 课程!
或者只使用正确的输入类型。
<input type="number" min="0.01" step="0.01" />