You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue新手求助:如何在created钩子中给Vee-validate加含正则的多验证规则

Fixing Vee-validate Phone Number Validation in Vue's created() Hook

Hey there! As someone who’s worked with Vee-validate quite a bit, I know how tricky the rule syntax can feel when you’re just starting out. Let’s get your phone number validation working properly—your original approach was close, but the rule formatting was off.

The core issue with your code is that you wrapped a rule object in a string, which Vee-validate can’t parse. Instead, you need to use either a pipe-separated rule string or a plain JavaScript object for the rules parameter. Here are two reliable solutions:

1. Using a Pipe-Separated Rule String

This is the quickest approach if you don’t need custom error messages yet. Combine the required rule with a regex that enforces exactly 11 digits:

created() {
  this.$validator.attach({
    name: "tel",
    // Use escaped backslashes in a regular string, or a template literal (no escapes needed)
    rules: "required|regex:/^\\d{11}$/"
  });

  // Alternative with template literal (cleaner syntax):
  // this.$validator.attach({
  //   name: "tel",
  //   rules: `required|regex:/^\d{11}$/`
  // });
}

The ^\\d{11}$ regex ensures exactly 11 digits—^ and $ act as anchors to prevent partial matches (like 10 or 12-digit numbers slipping through).

2. Using a Rule Object (With Custom Error Messages)

If you want more control (like tailored error messages for each rule), pass a plain object to rules—this is what you tried earlier, but without wrapping the object in quotes:

created() {
  this.$validator.attach({
    name: "tel",
    rules: {
      required: {
        rule: true,
        message: "手机号不能为空"
      },
      regex: {
        pattern: /^\d{11}$/,
        message: "请输入有效的11位手机号码"
      }
    }
  });
}

Quick Checklist to Avoid Common Issues:

  • Double-check that your input field has name="tel"—this is how Vee-validate links the rules to the correct field.
  • The regex anchors (^ and $) are critical here—without them, a 12-digit number would still pass because it contains 11 valid digits.
  • Based on your this.$validator usage, you’re on Vee-validate v2.x—these examples are tailored for that version. If you ever upgrade to v3+, the API uses useField/defineRule instead, but that’s a separate topic.

That should get your phone number validation working exactly as you need it!

内容的提问来源于stack exchange,提问作者Dolche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:53:29