我正在尝试使用jQuery和RegEx来执行年龄验证,但它似乎不起作用。我在RegEx上尝试了两次不同的尝试--其中一次在下面的代码中被注释掉。如果输入的年龄小于16岁,我将尝试使用以下代码显示一个错误:
jQuery.validator.addMethod("ageCheck",
function (value, element) {
//var age = /^([1-9]\d|[6-9]\d{2})$/;
var age = /^(1[6789]|[2-9]\d)$/;
return this.optional(element) || age.test(value);
},
"Age must be greater than or equal to 16");
发布于 2022-04-21 22:48:00
在评论中,我试图建议您一个更好的方法来处理年龄值的验证,而不是使用正则表达式。
不幸的是,您没有以更细粒度的方式提供任何不起作用的线索,而在您的问题中,您只包含了整个画面的一小部分。
所以我不能说你做错了什么,因为你没有分享任何细节。但是,我可以添加您在自定义验证器中缺少的内容。
因此,这是一个工作示例,将您的年龄字段包含在您可以提交的表单中,并且您可以看到错误消息(如果有的话)。验证将在输入文本失去焦点时触发。因此,没有必要强迫提交看到它的行动。
下面是我用来学习插件的一些参考资料:
//on document ready
$(document).ready(function() {
//defines your custom validator called ageRangeValidation
$.validator.addMethod(
'ageRangeValidation',
ageCheck,
'Age must be greater than or equal to 16'
);
//initializes the validation for the given form
$('#myform').validate({
//rules
rules: {
age: {
//including your custom defined validator bound to the age field here
ageRangeValidation: true
}
}
});
});
//your validation logic for the age field
const ageCheck = (value, element) => {
if (parseInt(value) >= 16)
return true;
else
return false;
}.error{
color: red;
font-style: italic;
display: block;
}
button[type='submit']{
margin-top: 20px;
cursor: pointer;
display: block;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<form id="myform">
<input type="text" id="age" name="age"/>
<label id="age-error" class="error" for="age"></label>
<button type="submit">Submit</button>
</form>
https://stackoverflow.com/questions/71960551
复制相似问题