我在输入表单中使用逗号作为小数点分隔符:
HTML:
<form id="myform">
<label for="field">Required, decimal number:</label>
<input class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
我想验证输入字段仅使用逗号作为小数点分隔符,并允许用户在逗号后仅输入 2 位小数(它是一种货币)。
JS:
$.validator.addMethod("mynumber", function (value, element) {
return this.optional(element) || /^(\d+|\d+,\d{1,2})$/.test(value);
}, "Por favor, introduza um número válido.");
$("#myform").validate({
debug: true,
rules: {
field: {
required: true,
mynumber: true
}
}
});
我已经使用 Keypress 将点替换为逗号。但是我怎样才能防止用户在逗号后插入超过 2 位小数呢? JS:
$("#field").keypress(function (evt) {
if (evt.which == 46) {
$(this).val($(this).val() + ',');
evt.preventDefault();
}
});
您可能会看到一个 JSFiddle here
最佳答案
$("#field").keypress(function (evt) {
if (evt.which == 46) {
$(this).val($(this).val() + ',');
evt.preventDefault();
}
//The input of more than 2 numbers after the decimal point is prevented
var foo = $(this).val();
if( !foo.match(/^(\d)*,?(\d){0,1}$/) ){
evt.preventDefault();
}
});
关于javascript - 在表单输入中指定逗号后的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21881001/