我使用jQuery验证插件执行客户端表单验证。效果很好。然而,我不知道确切的Regex,我无法实现我想要的。
我想添加3个不同的Regex,以便根据用户在输入字段中输入的内容显示3个不同的消息:
- Regex 1检测是否不是带有特定消息的数字
- Regex 2接受点或逗号表示小数
- 在特定的消息中,点或逗号后面只有2个小数
有很多相关的问题,但我已经尝试了很多答案,这些答案都不太好。
下面是一个工作代码片段
jQuery.validator.addMethod("decimal", function(value, element) {
// Validating Decimal Numbers
return this.optional(element) || /^([0-9]+[.]?[0-9]?[0-9]?|[0-9]+)$/g.test(value);
}, 'Please enter only numbers (format 0.00)');
jQuery.validator.addMethod("two_decimal", function(value, element) {
// require 2 decimals
return this.optional(element) || /^((d+(\.d{0,2})?)|((d*(.d{1,2}))))$/.test(value);
}, "Pleaser enter 2 numbers after dot");
// https://jqueryvalidation.org
$("#test_form").validate({
submitHandler: function(form) {
form.submit();
},
// rules, options, etc.,
onkeyup: function(element) {
// "eager" validation
this.element(element);
},
rules: {
decimal_number: {
required: true,
minlength: 1,
maxlength: 10,
decimal: true,
two_decimal: true
}
},
messages: {
montant_demande: {
required: "Please enter a number",
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="test_form" method="get" action="">
<fieldset>
<legend>Test</legend>
<p>
<label for="decimal_number">Number decimal</label>
<input id="decimal_number" name="decimal_number" minlength="2" type="text" required>
</p>
</fieldset>
</form>
如果您只想要数字,或带有逗号,
和点.
分隔符的小数,
参见下面的代码片段:
let decimalMessage = "";
jQuery.validator.addMethod("decimal", function(value, element) {
let decimal = /[^0-9.,]/g.test(value);
let decimalWithTwoDecimalNumber = /^d+([.,]d{2})?$/.test(value);
if(decimal) {
decimalMessage = 'Please enter only numbers (format 0.00)'
return this.optional(element);
}
if(decimalWithTwoDecimalNumber )
decimalMessage = 'Pleaser enter 2 numbers after dot'
return this.optional(element)||decimalWithTwoDecimalNumber
},function(params, element) {
return decimalMessage
});
// https://jqueryvalidation.org
$("#test_form").validate({
submitHandler: function(form) {
form.submit();
},
// rules, options, etc.,
onkeyup: function(element) {
// "eager" validation
this.element(element);
},
rules: {
decimal_number: {
required: true,
minlength: 1,
maxlength: 10,
decimal: true,
}
},
messages: {
montant_demande: {
required: "Please enter a number",
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="test_form" method="get" action="">
<fieldset>
<legend>Test</legend>
<p>
<label for="decimal_number">Number decimal</label>
<input id="decimal_number" name="decimal_number" minlength="2" type="text" required>
</p>
</fieldset>
</form>