vue密码正则验证表单验证_如何在Vue中使用表单验证

news/2024/7/5 2:16:42

vue密码正则验证表单验证

介绍 (Introduction)

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.

我们希望在用户单击“提交”按钮后立即显示错误消息,而无需向服务器发送响应,因为验证是在客户端进行的。 进行客户端验证并不会消除对服务器上的请求进行验证的需求,这也非常重要。

建立第一个例子 (Building the First Example)

With that established, let’s build our form. First, our App component will only render the Register component:

建立好之后,让我们建立表格。 首先,我们的App组件将仅呈现Register组件:

<div id="app">
  <div>
    <Register />
  </div>
</div>

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组件,我们要显示一个带有输入字段的表单:

<div>
    <h2>Register</h2>

    <form @submit.prevent="register" method="post">
      <div>
        <label>Name:</label>
        <input type="text" v-model="user.name" />
        <div>{{ errors.name }}</div>
      </div>
      <div>
        <label>Phone:</label>
        <input type="text" v-model="user.phone" />
        <div>{{ errors.phone }}</div>
      </div>
      <div>
        <label>Email:</label>
        <input type="text" v-model="user.email" />
        <div>{{ errors.email }}</div>
      </div>
      <div>
        <label>Password:</label>
        <input type="password" v-model="user.password" />
        <div>{{ errors.password }}</div>
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  </div>

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:

对于电子邮件和电话号码等唯一字段,我们使用正则表达式来确保其匹配特定的模式。 每个验证器都是一个函数,它将接收输入字段作为参数。 从上面可以看到,每个函数都返回validerror 。 这就是我们用来确定是否应提交表格的方式。 为了看到实际效果,这是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.

当所有字段都返回validtrue ,我们可以继续提交表单。 对于本教程,我们将显示一个警告框。

使用Joi (Using Joi)

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和遇到的错误。 如果没有错误,我们将像以前一样显示警报框。

结论 (Conclusion)

VeeValidate and Vuelidate are alternatives you can also make use of when handling form validation in your Vue application.

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

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-form-validation-in-vue

vue密码正则验证表单验证


http://www.niftyadmin.cn/n/3649234.html

相关文章

使用SharedStore的Python实现方法

打算在我的QTP framework中的HTML reporting里面加入detailed steps&#xff0c;想到了早期翻译的Tarun的文章中提到的一个工具&#xff1a;Shared Store 由于是COM组件&#xff0c;所以可以在python中实现 &#xff08;我的HTML reporting也是用python实现的&#xff09; 以…

[收藏]wuvist经典讲解MSNMessenger的四个联系人列表

原文&#xff1a;http://www.blogwind.com/wuvist/comment.aspx?article_id7004MSN其实有四个列表&#xff1a;ForwardList&#xff0c;AllowedList&#xff0c;ReverseList&#xff0c;跟BlockedList。我们平时看到的联系人列表其实只是&#xff1a;ForwardList而已。当我们看…

Ubuntu 11 安装Subversion成功记

综合了几个网页信息&#xff0c;结合自己的理解&#xff0c;在Ubuntu11上搭建成功了svn server 第一步&#xff1a;安装apache2 libapache2-svn subversion sudo apt-get install apache2 sudo apt-get install subversion sudo apt-get install libapache2-svn安装完后按照…

gatsby_Gatsby更快的WordPress网站

gatsbyTalk about the latest cutting-edge web technologies, and you find some impressive names like React.js, Vue.js, Next.js, and so on. They have opened new gateways and approaches to building websites that can serve content to users quickly. 谈论最新的前…

经典面试问题:12小球问题算法(源码)

(文档请参考&#xff1a;http://blog.csdn.net/CXXSoft/archive/2006/09/28/1299731.aspx)3、 运行效果4、 算法源码...{ 作品名称: 小球问题通用解决方案 开发作者: 成晓旭 开发时间: 2003年01月22日 完成时间: 2003年01月23日 修改时间1: 2003年11…

three react_使用react-three-fiber在React中编写Three.js

three reactSo you want to write some 3D graphics/animations in your React apps using three.js? Let’s see how we can do just that, leveraging the react-three-fiber library. 那么您想使用three.js在React应用中编写一些3D图形/动画吗&#xff1f; 让我们看看如何利…

Ubuntu 安装Postgres数据库,Windows 安装PgAdmin进行远程管理,Django远程连接 手记

Ubuntu通过SSH操作&#xff1a; 1. 安装postgres ~$ sudo apt-get install postgresql 2. 添加数据库用户&#xff1a;sudo -u postgres createuser -P YOURNAME3. 别忘了配置密码&#xff0c;作为超级用户。4. 创建用户名对应的数据库sudo -u postgres createdb YOURNAME …

通用网页数据采集系统的架构和运行机理

VersionDateCreatorDescription1.0.0.12004-9-06郑昀 掌上灵通草稿摘要&#xff1a;本文档详细介绍了网页数据采集系统的架构和运行机理。第一章简单介绍了Spider的设计意图和模块构成。第二章简单介绍了Spider.Crawler层如何抓取网页并落地。第三章简单介绍了Spider.Parser层如…