如何在 Vue 中使用表单验证

介绍

几乎每个Web应用程序都以某种方式使用表单,因为这些开发人员总是必须处理表单验证。如果你是一个新的开发人员,你可能很难决定如何最好地解决这个问题。

在本教程中,我们将学习如何通过Vue在您的表单中实现表单验证。

我们希望在用户点击提交按钮后显示错误消息 - 无需向服务器发送回复 - 因为验证是在客户端。

建立第一個例子

有了这一点,让我们构建我们的表格,首先,我们的应用程序组件只会显示注册组件:

1<div id="app">
2  <div>
3    <Register />
4  </div>
5</div>

脚本部分将看起来像这样:

1new Vue({
2  el: "#app"
3})

对于注册表组件,我们要显示一个带输入字段的表格:

 1<div>
 2    <h2>Register</h2>
 3
 4    <form @submit.prevent="register" method="post">
 5      <div>
 6        <label>Name:</label>
 7        <input type="text" v-model="user.name" />
 8        <div>{{ errors.name }}</div>
 9      </div>
10      <div>
11        <label>Phone:</label>
12        <input type="text" v-model="user.phone" />
13        <div>{{ errors.phone }}</div>
14      </div>
15      <div>
16        <label>Email:</label>
17        <input type="text" v-model="user.email" />
18        <div>{{ errors.email }}</div>
19      </div>
20      <div>
21        <label>Password:</label>
22        <input type="password" v-model="user.password" />
23        <div>{{ errors.password }}</div>
24      </div>
25      <div>
26        <button type="submit">Submit</button>
27      </div>
28    </form>
29  </div>

.prevent 方法用于在提交时阻止表单的默认行为. 表单有四个输入字段为姓名,电子邮件,电话和密码. 所有这些都需要自己的验证。

由于每个字段都是独一无二的,我们需要确保验证符合它们的独特性。 一般来说,没有一个字段应该是空的。 我们可以使用!field.length来检查此情况,其中字段将等同于我们所拥有的任何输入字段。 为了保持我们的代码清洁,验证器将被定义在Vue实例之外。 如果您在使用Vue CLI的应用程序中构建此功能,则意味着您将有验证器在一个单独的文件中。

 1const validateName = name => {
 2  if (!name.length) {
 3    return { valid: false, error: "This field is required" };
 4  }
 5  return { valid: true, error: null };
 6};
 7
 8const validatePhone = phone => {
 9  if (!phone.length) {
10    return { valid: false, error: 'This field is required.' };
11  }
12
13  if (!phone.match(/^[+][(]?[0-9]{1,3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,7}$/gm)) {
14    return { valid: false, error: 'Please, enter a valid international phone number.' };
15  }
16
17  return { valid: true, error: null };
18}
19
20const validateEmail = email => {
21  if (!email.length) {
22    return { valid: false, error: "This field is required" };
23  }
24  if (!email.match(/^\w+([.-]?\w+)_@\w+(_[_.-]?\w+)_(.\w{2,3})+$/)) {
25    return { valid: false, error: "Please, enter a valid email." };
26  }
27  return { valid: true, error: null };
28};
29
30const validatePassword = password => {
31  if (!password.length) {
32    return { valid: false, error: "This field is required" };
33  }
34  if (password.length < 7) {
35    return { valid: false, error: "Password is too short" };
36  }
37  return { valid: true, error: null };
38};

对于电子邮件和电话号码等独特的字段,我们使用regex来确保它匹配特定模式。 每个验证器是将输入字段作为参数接收的函数。 正如您从上方看到的那样,每个函数返回有效错误。 这就是我们将用来确定表单是否应该提交的函数。 为了看到在行动中,这里是注册组件的样子:

 1Vue.component('register', {
 2  template: '#register',
 3  data() {
 4    return {
 5      user: {
 6        email: '',
 7        password: '',
 8        name: '',
 9        phone: ''
10      },
11      valid: true,
12      success: false,
13      errors: {},
14      message: null
15    }
16  },
17  methods: {
18
19    register() {
20      this.errors = {}
21
22      const validName = validateName(this.user.name);
23      this.errors.name = validName.error;
24      if (this.valid) {
25        this.valid = validName.valid
26      }
27
28      const validPhone = validatePhone(this.user.phone);
29      this.errors.phone = validPhone.error;
30      if (this.valid) {
31        this.valid = validPhone.valid
32      }
33
34      const validEmail = validateEmail(this.user.email);
35      this.errors.email = validEmail.error;
36      if (this.valid) {
37        this.valid = validEmail.valid
38      }
39
40      const validPassword = validatePassword(this.user.password)
41      this.errors.password = validPassword.error
42      if (this.valid) {
43        this.valid = validPassword.valid
44      }
45
46      if (this.valid) {
47        alert('HURRAAYYY!! :-)\n\n' + JSON.stringify(this.user))
48      }
49    }
50  }
51})

如果验证器返回任何一个字段的错误,则返回的错误将保存到errors.fieldName - 其中fieldName是输入字段的名称,然后显示给用户查看错误。

当所有字段返回有效真实,我们可以继续提交表单。

使用Joi

Joi 允许您构建 JavaScript 对象的架构,可用于验证输入. 它通常在使用 Express 和 Restify 时使用。

这里是方案:

 1import Joi from "joi";
 2
 3const phoneRegex = /^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,7}$/gm;
 4const phone = Joi.string().regex(phoneRegex)
 5  .options({
 6    language: {
 7      string: {
 8        regex: {
 9          base: 'must be a valid phone number'
10        }
11      }
12    }
13  });
14
15const userValidation = {};
16userValidation.create = {
17  first_name: Joi.string().min(2).max(24).required(),
18  email: Joi.string().email().required(),
19  password: Joi.string().min(7).required(),
20  phone: phone.required()
21};

然后,我们可以使用注册表组件中的方案来验证用户的输入:

 1Vue.component('register', {
 2  template: '#register',
 3  data() {
 4    return {
 5      user: {
 6        name: '',
 7        email: '',
 8        password: '',
 9        phone: ''
10      },
11      valid: false,
12      success: false,
13      errors: {},
14      issues: {}
15    }
16  },
17  methods: {
18    // method that validates the user input using the schema
19    validate(value, schema) {
20      const result = Joi.validate(value, schema, { abortEarly: false });
21      if (result.error) {
22        result.error.details.forEach((error) => {
23          this.issues[error.path[0]] = error.message;
24        });
25        return false;
26      }
27      return true;
28    },
29
30    register() {
31      // validation method is called and passed the inputs and schema
32      this.validate(this.user, userValidation.create);
33        if (Object.keys(this.issues).length > 0) {
34          this.errors = this.issues;
35          return false;
36        }
37        alert('HURRAAYYY!! :-)\n\n' + JSON.stringify(this.user))
38    }
39  }
40})

我们声明一种验证方法,它将接受用户输入和我们定义的方案。如果在验证后发现错误,我们将返回一个并发现错误。

结论

VeeValidate 和 Vuelidate 是您在 Vue 应用程序中处理表单验证时也可以使用的替代方案。

Published At
Categories with 技术
Tagged with
comments powered by Disqus