jQuery Validation Plugin:使用逗号作为小数分隔符验证十进制数 [英] jQuery Validation Plugin: validate decimal number with comma as decimal separator
本文介绍了jQuery Validation Plugin:使用逗号作为小数分隔符验证十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
JS:
$( "#myform" ).validate({
rules: {
field: {
required: true,
number: true
}
}
});
这需要字段field中的有效数字。但是,当使用逗号作为小数分隔符时,它不起作用。例如:10,25不被视为有效数字。
This is requiring a valid number in field "field". However, when using comma as decimal separator, it doesn't work. Eg: 10,25 is not considered a valid number.
我从中提取此示例验证插件
您还可以在此处看到现场 JSFiddle 。
我想在验证之前我必须将输入(从逗号转换为点小数分隔符),但是如何?
I guess I will have to convert the input (from comma to dot decimal separator) before it is validated, but how?
推荐答案
您可以使用模式规则传递自定义正则表达式模式,例如
You can use the pattern rule to pass a custom regex pattern like
$("#myform").validate({
//for debug only
debug: true,
rules: {
field: {
required: true,
pattern: /^(\d+|\d+,\d{1,2})$/
}
},
messages: {
field: {
pattern: 'Please use the proper pattern'
}
}
});
演示:小提琴
如果是重复模式,请创建自定义验证规则
If it is a repeated pattern create a custom validation rule
jQuery.validator.addMethod("mynumber", function (value, element) {
return this.optional(element) || /^(\d+|\d+,\d{1,2})$/.test(value);
}, "Please specify the correct number format");
$("#myform").validate({
//for debug only
debug: true,
rules: {
field: {
required: true,
mynumber: true
}
}
});
演示:小提琴
这篇关于jQuery Validation Plugin:使用逗号作为小数分隔符验证十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文