本文共 8476 字,大约阅读时间需要 28 分钟。
vue密码正则验证表单验证
Almost every web application makes use of forms in some way, as such developers always have to tackle form validations. If you are a new developer, it can be hard deciding how best to approach this. Depending on the stack you are using, there are many of options to choose from.
几乎每个Web应用程序都以某种方式使用表单,因为此类开发人员始终必须处理表单验证。 如果您是新开发人员,可能很难决定如何最好地实现这一目标。 根据您使用的堆栈,有许多选项可供选择。
In this tutorial we will learn how to you can implement form validation in your form with Vue.
在本教程中,我们将学习如何使用Vue在表单中实现表单验证。
We want to show the error message as soon as the user hits the submit button—no need to send a response to the server—as the validation is on the client-side. Having a client-side validation does not remove the need of validating requests on your server—that is very important too.
我们希望在用户单击“提交”按钮后立即显示错误消息,而无需向服务器发送响应,因为验证是在客户端进行的。 进行客户端验证并不会消除对服务器上的请求进行验证的需求,这也非常重要。
With that established, let’s build our form. First, our App component will only render the Register component:
建立好之后,让我们建立表格。 首先,我们的App组件将仅呈现Register组件:
The script section will look like this:
脚本部分如下所示:
new Vue({ el: "#app"})
For the Register component we want to show a form with inputs fields:
对于Register组件,我们要显示一个带有输入字段的表单:
Register
The .prevent
method is used to stop the default behavior of the form when a submission is made. The form has four inputs field for name, email, phone, and password. All of these will need their own validations. If there is an error with any of the inputs, it will be displayed below the input field.
.prevent
方法用于在提交时停止表单的默认行为。 该表格有四个输入字段,分别是名称,电子邮件,电话和密码。 所有这些都需要自己的验证。 如果任何输入有错误,它将显示在输入字段下方。
Since each field is unique, we need to ensure the validation is suited to match their uniqueness. A general one is that none of the fields should be empty. We can check for this using !field.length
, where field
will equate to any of the input fields we have. To keep our code clean, the validators will be defined outside the Vue instance. If you are building this in an app that is scaffolded using Vue CLI, it means you’ll have the validators in a separate file.
由于每个字段都是唯一的,因此我们需要确保验证适合于匹配其唯一性。 一般情况下,所有字段都不为空。 我们可以使用!field.length
进行检查,其中field
等于我们拥有的任何输入字段。 为了保持我们的代码整洁,将在Vue实例外部定义验证器。 如果要在使用Vue CLI搭建支架的应用程序中构建此文件,则意味着您将在单独的文件中拥有验证程序。
const validateName = name => { if (!name.length) { return { valid: false, error: "This field is required" }; } return { valid: true, error: null };};const validatePhone = phone => { if (!phone.length) { return { valid: false, error: 'This field is required.' }; } if (!phone.match(/^[+][(]?[0-9]{1,3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,7}$/gm)) { return { valid: false, error: 'Please, enter a valid international phone number.' }; } return { valid: true, error: null };}const validateEmail = email => { if (!email.length) { return { valid: false, error: "This field is required" }; } if (!email.match(/^\w+([.-]?\w+)_@\w+(_[_.-]?\w+)_(.\w{2,3})+$/)) { return { valid: false, error: "Please, enter a valid email." }; } return { valid: true, error: null };};const validatePassword = password => { if (!password.length) { return { valid: false, error: "This field is required" }; } if (password.length < 7) { return { valid: false, error: "Password is too short" }; } return { valid: true, error: null };};
For unique fields like email and phone number, we make use of regex to make sure it matches a specific pattern. Each validator is a function that will receive the input field as a parameter. As you can see from above, each function returns valid
and error
. This is what we will use to determine if a form should be submitted. To see that in action, here is how the Register component will look:
对于电子邮件和电话号码等唯一字段,我们使用正则表达式来确保其匹配特定的模式。 每个验证器都是一个函数,它将接收输入字段作为参数。 从上面可以看到,每个函数都返回valid
和error
。 这就是我们用来确定是否应提交表格的方式。 为了看到实际效果,这是Register组件的外观:
Vue.component('register', { template: '#register', data() { return { user: { email: '', password: '', name: '', phone: '' }, valid: true, success: false, errors: {}, message: null } }, methods: { register() { this.errors = {} const validName = validateName(this.user.name); this.errors.name = validName.error; if (this.valid) { this.valid = validName.valid } const validPhone = validatePhone(this.user.phone); this.errors.phone = validPhone.error; if (this.valid) { this.valid = validPhone.valid } const validEmail = validateEmail(this.user.email); this.errors.email = validEmail.error; if (this.valid) { this.valid = validEmail.valid } const validPassword = validatePassword(this.user.password) this.errors.password = validPassword.error if (this.valid) { this.valid = validPassword.valid } if (this.valid) { alert('HURRAAYYY!! :-)\n\n' + JSON.stringify(this.user)) } } }})
If a validator returns an error for any of the fields, the error returned is saved in the errors.fieldName
—where fieldName
is the name of the input field, and then displayed for the user to see what went wrong.
如果验证器针对任何字段返回错误,则返回的错误将保存在errors.fieldName
-其中fieldName
是输入字段的名称,然后显示给用户查看出了什么问题。
When all fields return valid
as true
, we can then go ahead to submit the form. For this tutorial, we are displaying an alert box.
当所有字段都返回valid
为true
,我们可以继续提交表单。 对于本教程,我们将显示一个警告框。
Joi allows you to build schemas for JavaScript objects, which can be used to validate inputs. It is often used when working with Express and Restify. We can use it in this tutorial by defining a schema for our Register component.
Joi允许您为JavaScript对象构建模式,该模式可用于验证输入。 在使用Express和Restify时经常使用它。 我们可以在本教程中通过为Register组件定义一个架构来使用它。
Here is the schema:
这是模式:
import Joi from "joi";const phoneRegex = /^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,7}$/gm;const phone = Joi.string().regex(phoneRegex) .options({ language: { string: { regex: { base: 'must be a valid phone number' } } } });const userValidation = {};userValidation.create = { first_name: Joi.string().min(2).max(24).required(), email: Joi.string().email().required(), password: Joi.string().min(7).required(), phone: phone.required()};
We can then use the schema in our Register component to validate the inputs of the user:
然后,我们可以使用Register组件中的模式来验证用户的输入:
Vue.component('register', { template: '#register', data() { return { user: { name: '', email: '', password: '', phone: '' }, valid: false, success: false, errors: {}, issues: {} } }, methods: { // method that validates the user input using the schema validate(value, schema) { const result = Joi.validate(value, schema, { abortEarly: false }); if (result.error) { result.error.details.forEach((error) => { this.issues[error.path[0]] = error.message; }); return false; } return true; }, register() { // validation method is called and passed the inputs and schema this.validate(this.user, userValidation.create); if (Object.keys(this.issues).length > 0) { this.errors = this.issues; return false; } alert('HURRAAYYY!! :-)\n\n' + JSON.stringify(this.user)) } }})
We declare a validate
method that will accept the user inputs and the schema we have defined. If errors are found after the validation we will return a false
and the errors encountered. If there are no errors, we display the alert box as we did before.
我们声明一个validate
方法,该方法将接受用户输入和我们定义的模式。 如果在验证后发现错误,我们将返回false
和遇到的错误。 如果没有错误,我们将像以前一样显示警报框。
VeeValidate and Vuelidate are alternatives you can also make use of when handling form validation in your Vue application.
VeeValidate和Vuelidate是您在Vue应用程序中处理表单验证时也可以使用的替代方法。
翻译自:
vue密码正则验证表单验证
转载地址:http://uvhgb.baihongyu.com/