使用Regex创建自定义验证规则

时间:2019-12-16 06:43:50

标签: jquery regex

我在html表单中有一个帐户汇率输入框,我需要使用jquery验证插件来验证输入。帐户费率输入框的属性是

1)输入负值(例如-1000)时,它应显示一条错误消息,提示用户输入一个大于或等于0的值。

2)输入字母或特殊字符(例如&%#)时,它应该显示一条错误消息,告诉用户输入数字。

我尝试使用jquery验证插件的'digits'和'min'值,但是,当输入-1000时,显示的错误消息与输入字母/特殊字符时显示的消息相同。但是,我需要错误消息告诉用户输入一个大于或等于0的值。

我该如何处理?我认为我需要使用Regex吗?如果可以,怎么办?

1 个答案:

答案 0 :(得分:0)

在顶部加载这两个CDN:

https://code.jquery.com/jquery-3.4.1.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js

然后在script标签中输入js代码。不要忘记在此代码中更改表单的名称:

    $(function() {
        $("form[name='name-of-your-form']").validate({

             rules: {
              // The key name on the left side is the name attribute
              // of an input field. Validation rules are defined
              // on the right side
              accountrate:{
                required: true,
                minlength: 0,
                digits: true,
              }
            },
            // Specify validation error messages
            messages: {
                accountrate:{
                    required: "This field is required",
                    minlength: "Please enter a minimum length",
                    digits: "Please enter digits"
                }
            },
            // Make sure the form is submitted to the destination defined
            // in the "action" attribute of the form when valid
            submitHandler: function(form) {
              form.submit();
            }
        });
    });
相关问题