vue.js表单验证_Vue.js中的模板驱动表单验证

本文介绍了如何使用VeeValidate插件在Vue.js中实现模板驱动的表单验证。通过VeeValidate,我们可以方便地设置验证规则,检查表单输入,并显示错误消息。示例中展示了创建一个简单的注册表单,包括用户名、邮箱、密码和确认密码等字段的验证过程。
摘要由CSDN通过智能技术生成

vue.js表单验证

Form validation (or more correctly, form field validation) forces a user to fill out all required fields in a web form. The validation is typically done where the developer can set up rules. For example: If the name field is blank, take the user back to the form and display an error message.

表单验证(或更正确地说,表单字段验证)会强制用户填写Web表单中的所有必填字段。 验证通常在开发人员可以设置规则的地方进行。 例如:如果名称字段为空白,则将用户带回到表单并显示错误消息。

Template driven validation is a type of form validation where validation rules are set directly in the form elements using directives.

模板驱动的验证是一种表单验证,其中,使用指令直接在表单元素中设置验证规则。

To implement template driven validations in Vue.js, we can use VeeValidate. VeeValidate is a plugin for Vue.js that allows you to validate input fields and display errors.

为了在Vue.js中实现模板驱动的验证,我们可以使用VeeValidate。 VeeValidateVue.js的插件,可让您验证输入字段并显示错误。

我们将建立什么 ( What We Will build )

At the end of this piece, we will build a simple registration form which uses VeeValidate to validate its form input. Here is a pictorial view of what we will build.

在本文的最后,我们将构建一个简单的注册表单,该表单使用VeeValidate来验证其表单输入。 这是我们将要构建的图形视图。

VeeValidate入门 ( Getting Started With VeeValidate )

First, we need to grab Vue and the VeeValidate library.

首先,我们需要获取Vue和VeeValidate库。

Let us grab the browser build for Vue.js which is available here.

让我们来获取适用于Vue.js的浏览器版本,可在此处获得

Next, we will grab the browser build for VeeValidate which is available via jsdeliver here.

接下来,我们将获取VeeValidate的浏览器版本,可通过jsdeliver here获得

Create a new file called register.html and add:

创建一个名为register.html的新文件并添加:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Vue Template Form Validation</title>
</head>
<body>
</body>
<!-- include the Vue.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<!-- include the VeeValidate library -->
<script src="https://cdn.jsdelivr.net/npm/vee-validate@latest/dist/vee-validate.js"></script>
<script>
// Notify vue about the VeeValidate plugin
 Vue.use(VeeValidate);
</script>

The code above shows how easy it is to include VeeValidate into our Vue project. Vue.js is notified that it can use the VeeValidate plugin at the line that says Vue.use(VeeValidate).

上面的代码显示了将VeeValidate包含到我们的Vue项目中是多么容易。 通知Vue.js它可以在显示Vue.use(VeeValidate)的行上使用VeeValidate插件。

VeeValidate规则 ( VeeValidate Rules )

A VeeValidate rule is one that sets limits or conditions on what can be entered in one or more fields. Validation rules are checked when you update a record containing fields requiring validation. If the rule is violated, a trappable error occurs. How do you use a rule? Just apply the v-validate directive on your input and pass a string value which is a list of validations separated by a pipe. For example, we will use the required and the email validators:

VeeValidate规则是一项针对可以在一个或多个字段中输入的内容设置限制或条件的规则。 更新包含要求验证的字段的记录时,将检查验证规则。 如果违反该规则,则会发生可捕获的错误。 您如何使用规则? 只需在您的输入上应用v-validate指令,然后传递一个字符串值,该值是一个由pipe分隔的验证列表。 例如,我们将使用requiredemail验证程序:

<input v-validate="'required|email'" type="text" name="email">

Alternatively you can pass an object for more flexibility:

另外,您可以传递对象以提高灵活性:

<input v-validate="{ required: true, email: true, regex: /[0-9]+/ }" type="text" name="email">

Now every time the input changes, the validator will run the list of validations from left to right, populating the errors helper object whenever an input fails validation.

现在,每次输入更改时,验证器都会从左到右运行验证列表,每当输入验证失败时,都会填充错误帮助器对象。

As at the time of writing this tutorial, VeeValidate ships with 30 rules for form validation with an option of creating your own rules. You can take a peep at what rules are available here.

在撰写本教程时,VeeValidate附带了30条用于表单验证的规则,并提供了创建自己的规则的选项。 您可以看一下这里有哪些可用规则。

VeeValidate错误 ( VeeValidate Errors )

By default, VeeValidate provides us with a variable errors which is injected into the data section of the Vue component by the plugin. When a form validation fails, VeeValidate populates this errors variable with an array containing objects of failed validations, which can be accessed this way:

默认情况下,VeeValidate为我们提供了变量errors ,该errors由插件注入Vue组件的data部分。 当表单验证失败时,VeeValidate将使用包含验证失败对象的数组填充此errors变量,可以通过以下方式访问该对象:

//check if an input has errors
this.errors.has(Inputname)
//return the first error of an input
this.errors.first(Inputname)

However, to use this method, some things must be put into consideration.

但是,要使用此方法,必须考虑一些因素。

  • The name attribute must be specified. It serves as an identifier for VeeValidate to refer to. You can use data-vv-name if, for some reason, you can’t use name attribute in your template.

    必须指定name属性。 它用作VeeValidate引用的标识符。 如果由于某种原因不能在模板中使用name属性,则可以使用data-vv-name。

VeeValidate自定义验证 ( VeeValidate Custom Validation )

While VeeValidate ships with around 30 rules, these rules might not do justice to your form as intended. What if I need a custom validation that VeeValidate does not come with? For example, what if I want to validate that a username is unique in my database? VeeValidate allows you to write custom validation rules and messages. Take a look at the code below for example:

尽管VeeValidate附带了大约30条规则,但这些规则可能无法按预期使您的表单公正。 如果我需要VeeValidate随附的自定义验证怎么办? 例如,如果我想验证用户名在数据库中是唯一的怎么办? VeeValidate允许您编写自定义验证规则和消息。 看下面的代码,例如:

//declare an array of some usernames user must not input
 var username = [
    'admin',
    'password',
    'administartor'
]
//create new rule
const newrule = {
// will be added to default English messages.
  getMessage(field, params, data) {
      return (data && data.message) || 'Something went wrong';
  },
  // Returns a Boolean or a Promise.
  validate(value) {
    return new Promise(resolve => {
      resolve({
        valid: username.includes(value.toLowerCase()) ? false : !! value,
        data: { message: `${value} has already been taken` }
      });
    });
  }
};

The important things to notice in the code below are:

以下代码中需要注意的重要事项是:

  • The getMessage method in the object is used to return a custom error message. The message can either be passed directly or passed via a variable from called data from the validate method

    对象中的getMessage方法用于返回自定义错误消息。 消息可以直接传递,也可以通过来自validate方法调用数据的变量传递
  • The validate method in the object returns a boolean, an object or a promise. If it returns an object, the valid property must be present with a boolean value. This boolean value is what is checked to see if the form is valid or not. In our case, we checked if the value is included in the list of usernames we do not want people selecting from.

    对象中的validate方法返回一个布尔值,一个对象或一个Promise。 如果它返回一个对象,则有效属性必须带有布尔值。 此布尔值是检查表单是否有效的值。 在我们的案例中,我们检查了该值是否包含在我们不希望用户选择的用户名列表中。

Now we have a new rule. Does VeeValidate automatically know about this rule? No. How do we tell VeeValidate that it can use this new rule we just created? By extending the default Validator and passing the new rule into it:

现在我们有了一条新规则。 VeeValidate是否自动知道此规则? 否。我们如何告诉VeeValidate它可以使用我们刚刚创建的新规则? 通过扩展默认的验证器并将新规则传递给它:

VeeValidate.Validator.extend('checkuser',newrule);

In this snippet, we just extended the VeeValidate validator with our own custom validator named checkuser. So we can call the Validator for any input this way:

在此代码片段中,我们仅使用了自己的名为checkuser的自定义验证器扩展了VeeValidate验证器。 因此,我们可以通过以下方式为任何输入调用验证器:

<input v-validate="'checkuser'" type="text" name="username">

验证简单的注册页面 ( Validating A Simple Registration Page )

Let us whip up a small demo. We will be validating a simple registration page. Move back into the file created at the beginning of this exercise called register.html and add the following HTML:

让我们整理一个小演示。 我们将验证一个简单的注册页面。 返回到在本练习开始时创建的名为register.html的文件,并添加以下HTML:

<body>
        <div class="container">
            <div class="row main">
                <div class="main-login main-center">
                <h5>Sign up once and watch any of our free demos.</h5>
                    <form id="signup-form" @submit.prevent="processForm">


                        <div class="form-group">
                            <label for="name" class="cols-sm-2 control-label">Your Name</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
                  <input type="text" name="name" placeholder="Name" :class="{ 'form-control': true, 'is-danger': errors.has('name') }" v-model="name" v-validate="'required|alpha'">

                                </div>
                 <span v-show="errors.has('name')" class="help is-danger">{{ errors.first('name') }}</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="email" class="cols-sm-2 control-label">Your Email</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
                                    <input type="email" :class="{ 'form-control': true, 'is-danger': errors.has('email') }" name="email" placeholder="my@email.com" v-model="email" v-validate="'required|email'">

                </div>
                <span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="username" class="cols-sm-2 control-label">Username</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
                                        <input type="text" :class="{ 'form-control': true, 'is-danger': errors.has('username') }" name="username" placeholder="Enter your username" v-model="username" v-validate="'required|checkuser'">
                                </div>
                 <span v-show="errors.has('username')" class="help is-danger">{{ errors.first('username') }}</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="cols-sm-2 control-label">Password</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
                                    <input type="password" :class="{ 'form-control': true, 'is-danger': errors.has('password') }" name="password" placeholder="Enter a password" v-model="password" v-validate="'required|min:6'">
                                </div>
                <span v-show="errors.has('password')" class="help is-danger">{{ errors.first('password') }}</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="confirm" class="cols-sm-2 control-label">Confirm Password</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>

                                <input v-validate="'required|confirmed:password'" name="password_confirmation" type="password" :class="{ 'form-control': true, 'is-danger': errors.has('password') }" placeholder="Password, Again" data-vv-as="password">
                </div>
                <span v-show="errors.has('password_confirmation')" class="help is-danger">{{ errors.first('password_confirmation') }}</span>
                            </div>
                        </div>

                        <div class="form-group ">
                            <button id="button" :disabled="errors.any()" class="btn btn-primary btn-lg btn-block login-button">Register</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>

In the code block above, we have 5 input elements which are:

在上面的代码块中,我们有5个输入元素,它们是:

  • Name: The name of the user registering. Note that the v-validate directive was also added to it, specifying required|alpha which means the input is required and can only contain alphabetic characters. Also notice a span element just after the input which shows up when errors.has('name') is true, courtesy of the v-show directive. It then displays the first error for that input via errors.first('name')

    名称:注册用户的名称。 请注意,还向其中添加了v-validate指令,指定了required|alpha ,这意味着输入是必需的,并且只能包含字母字符。 还要注意输入之后的span元素,这是在errors.has('name')为true时显示的,这是由v-show指令提供的。 然后通过errors.first('name')显示该输入的第一个错误。
  • Email: The email of the user registering. Note that the v-validate directive was also added to it, specifying required|email which means the input is required and must contain a valid email. Like the name input, this also has a span input attached in similar fashion.

    电子邮件:注册用户的电子邮件。 请注意,还向其中添加了v-validate指令,指定了required|email ,这表示输入是必需的,并且必须包含有效的电子邮件。 像名称输入一样,它也以类似的方式附加了跨度输入。
  • Username: The general username for the user registering. Note that we have something a bit different in the v-validate directive here. We passed in a rule called checkuser. Remember this custom validator that we made? Here we see it in action. Like the name and email input, this also has a span input attached in a similar fashion.

    用户名:用户注册的常规用户名。 请注意,这里的v-validate指令有些不同。 我们传入了一个名为checkuser的规则。 还记得我们制作的这个自定义验证器吗? 在这里,我们看到了它的作用。 像名称和电子邮件输入一样,它也以类似的方式附加了跨度输入。
  • Password: The password the user registering must set. In the v-validate directive of this input, we have another rule specified min:6. This tells VeeValidate that the password must not be lesser than 6 characters. Like the name, email and username input, this also has a span input attached in a similar fashion.

    密码:注册用户必须设置的密码。 在此输入的v-validate指令中,我们指定了另一个规则min:6 。 这告诉VeeValidate密码不得少于6个字符。 像名称,电子邮件和用户名输入一样,它也以类似的方式附加了跨度输入。
  • Password_confirmation: Here we want the user to confirm his password. This is helpful, so he doesn't make a mistake in his password unknowingly. Notice that in the v-validate directive, we passed in confirmed:password as one of the rules? This tells VeeValidate that the value of this input must equal the value of the password input. Like the name, email and username input, this also has a span input attached in a similar fashion.

    密码确认:我们希望用户在此确认他的密码。 这很有用,因此他不会在不知不觉中输入密码的错误。 注意,在v-validate指令中,我们传入了confirmed:password作为规则之一? 这告诉VeeValidate,此输入的值必须等于密码输入的值。 像名称,电子邮件和用户名输入一样,它也以类似的方式附加了跨度输入。

Also, our markup consists of a button, which is used to submit the form. First, I want you to take a look at the Form declaration in the markup and notice the @submit.prevent="processForm". This prevents the form from refreshing or performing any other action when this button is clicked rather than the one defined in the processForm function in our Vue methods. Also, notice that in the button, we have a little condition for the disabled property of the button :disabled="errors.any()". The errors.any() is a method exposed by VeeValidate to verify if all validations were passed or not.

另外,我们的标记包含一个按钮,用于提交表单。 首先,我希望您看一下标记中的Form声明,并注意@submit.prevent="processForm" 。 当单击此按钮而不是在Vue方法中的processForm函数中定义的按钮时,这可以防止表单刷新或执行任何其他操作。 另外,请注意,在按钮中,按钮的disabled属性有一点条件:disabled =“ errors.any()”。 errors.any errors.any()是VeeValidate公开的一种方法,用于验证是否通过了所有验证。

Next, let's add some style to make it look great. Open a style tag and paste:

接下来,让我们添加一些样式以使其看起来很棒。 打开样式标签并粘贴:

#playground-container {
    height: 500px;
    overflow: hidden !important;
    -webkit-overflow-scrolling: touch;
}
body, html{
     height: 100%;
     background-repeat: no-repeat;
     background:url(https://i.ytimg.com/vi/4kfXjatgeEU/maxresdefault.jpg);
     font-family: 'Oxygen', sans-serif;
        background-size: cover;
}

.main{
     margin:50px 15px;
}

h1.title { 
    font-size: 50px;
    font-family: 'Passion One', cursive; 
    font-weight: 400; 
}

hr{
    width: 10%;
    color: #fff;
}

.form-group{
    margin-bottom: 15px;
}

label{
    margin-bottom: 15px;
}

input,
input::-webkit-input-placeholder {
    font-size: 11px;
    padding-top: 3px;
}

.main-login{
     background-color: #fff;
    /* shadows and rounded borders */
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);

}
.form-control {
    height: auto!important;
padding: 8px 12px !important;
}
.input-group {
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
}
#button {
    border: 1px solid #ccc;
    margin-top: 28px;
    padding: 6px 12px;
    color: #666;
    text-shadow: 0 1px #fff;
    cursor: pointer;
    -moz-border-radius: 3px 3px;
    -webkit-border-radius: 3px 3px;
    border-radius: 3px 3px;
    -moz-box-shadow: 0 1px #fff inset, 0 1px #ddd;
    -webkit-box-shadow: 0 1px #fff inset, 0 1px #ddd;
    box-shadow: 0 1px #fff inset, 0 1px #ddd;
    background: #f5f5f5;
    background: -moz-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f5f5f5), color-stop(100%, #eeeeee));
    background: -webkit-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
    background: -o-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
    background: -ms-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
    background: linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f5f5f5', endColorstr='#eeeeee', GradientType=0);
}
.main-center{
     margin-top: 30px;
     margin: 0 auto;
     max-width: 400px;
    padding: 10px 40px;
    background:rgb(123, 131, 134);
        color: #FFF;
    text-shadow: none;
    -webkit-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
-moz-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);

}
span.input-group-addon i {
    color: #009edf;
    font-size: 17px;
}

.login-button{
    margin-top: 5px;
}

.login-register{
    font-size: 11px;
    text-align: center;
}
.is-danger{
  color: red;
  font-weight: 700;
}
.help {
    background: white;
    }

Above are some CSS styles to make our page look great. Don't forget to add the following to your head tag:

上面是一些CSS样式,使我们的页面看起来很棒。 不要忘记在您的head标签中添加以下内容:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Above is the code to link bootstrap to our registration page. To make it much nicer.

上面的代码将引导程序链接到我们的注册页面。 为了更好。

Vue组件 (Vue Component)

Let us take a look at how our Vue Component should look now. Replace the script section where we have Vue.use(VeeValidate) with:

让我们看看我们的Vue组件现在应该看起来如何。 将具有Vue.use(VeeValidate)的脚本部分替换为:

// Notify vue about the VeeValidate plugin
Vue.use(VeeValidate);
//declare an array of some usernames user must not input
 var username = [
    'admin',
    'password',
    'administartor'
]
//create new rule
const newrule = {
// will be added to default English messages.
  getMessage(field, params, data) {
      return (data && data.message) || 'Something went wrong';
  },
    // Returns a Boolean or a Promise.
  validate(value) {
    return new Promise(resolve => {
      resolve({
        valid: username.includes(value.toLowerCase()) ? false : !! value,
        data: { message: `${value} has already been taken` }
      });
    });
  }
};
// Tell the Validator about the new rule
  VeeValidate.Validator.extend('checkuser',newrule);
    const signupForm = new Vue({
        el: '#signup-form',
        data: {
            name: '',
            email: '',
            username: '',
            password: ''
        },
        methods: {
            processForm: function() {
        //attempt validating all
                this.$validator.validateAll().then((result) => {
                    if (result) {
            //validation passed succesfully

                       alert('Form validated succesfully');
                    }
                });
            }
        }
    });

The code block is pretty similar. First we see the custom rule we created earlier on, extended it to the default validator and mounted our Vue instance. Let's move to the methods section and see what we have in our proessForm method. Here we call the $validator.validateAll() function, which is a method exposed by VeeValidate which tries to validate all inputs and then returns a promise. We then check if the validation was succesful and triggered an alert.

代码块非常相似。 首先,我们看到我们之前创建的自定义规则,将其扩展到默认验证器并挂载了我们的Vue实例。 让我们进入方法部分,看看我们的proessForm方法中有什么。 这里我们调用$validator.validateAll()函数,这是VeeValidate公开的方法,该方法尝试验证所有输入,然后返回Promise。 然后,我们检查验证是否成功并触发了警报。

If we open our template.html file in a browser, it should work as seen:

如果我们在浏览器中打开template.html文件,则该文件应如下所示工作:

Feel free to play with the demo here

随时在这里玩演示

结论 ( Conclusion )

In this article, we have seen how to validate form inputs using the template driven approach. VeeValidate has made it very simple to validate form inputs by exposing a v-validate directive as well as giving room to extend / add custom Validators.

在本文中,我们已经看到了如何使用模板驱动的方法来验证表单输入。 VeeValidate通过暴露v-validate指令以及扩展/添加自定义验证器的空间,使验证表单输入变得非常简单。

When next you need to validate forms in Vue, and you want it template driven, you now know the way to go.

接下来,您需要在Vue中验证表单并希望它由模板驱动,现在您知道要走的路了。

翻译自: https://scotch.io/tutorials/template-driven-form-validation-in-vuejs

vue.js表单验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值