首页  >  文章  >  web前端  >  详解vue和vue-validator实现表单验证功能

详解vue和vue-validator实现表单验证功能

小云云
小云云原创
2018-05-17 16:43:404159浏览

本文主要介绍了vue+vue-validator 表单验证功能的实现代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下,希望能帮助到大家。

下面给大家介绍vue+vue-validator 表单验证功能,具体代码如下所示:

1.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <title>Title</title> 
</head> 
<body> 
  <p id="app"> 
    <validator name="myForm"> 
      <form novalidate> 
        Zip: <input type="text" v-validate:zip="[&#39;required&#39;]"><br /> 
        <p> 
          <span v-if="$myForm.zip.required">Zip code is required.</span> 
        </p> 
      </form> 
    </validator> 
  </p> 
  <script src="https://unpkg.com/vue@1.0.26/dist/vue.min.js"></script> 
  <script src="https://cdn.bootcss.com/vue-validator/2.1.3/vue-validator.js"></script> 
  <script> 
    new Vue({ 
      el:"#app" 
    }) 
  </script> 
</body> 
</html>

2.

<!DOCTYPE html> 
<html> 
 <head> 
  <meta charset="utf-8"> 
  <title>radio button validation example</title> 
  <script src="../../node_modules/vue/dist/vue.js"></script> 
  <script src="../../dist/vue-validator.js"></script> 
  <style> 
   input.invalid { border-color: red; } 
   .errors { color: red; } 
  </style> 
 </head> 
 <body> 
  <p id="app"> 
   <h1>Survey</h1> 
   <validity-group field="fruits" v-model="validation" :validators="{ 
    required: { message: requiredErrorMsg } 
   }"> 
    <legend>Which do you like fruit ?</legend> 
    <input id="apple" type="radio" name="fruit" value="apple" @change="handleValidate" @focusin="handleValidate"> 
    <label for="apple">Apple</label> 
    <input id="orange" type="radio" name="fruit" value="orange" @change="handleValidate" @focusin="handleValidate"> 
    <label for="orange">Orage</label> 
    <input id="grape" type="radio" name="fruit" value="grage" @change="handleValidate" @focusin="handleValidate"> 
    <label for="grape">Grape</label> 
    <input id="banana" type="radio" name="fruit" value="banana" @change="handleValidate" @focusin="handleValidate"> 
    <label for="banana">Banana</label> 
    <ul class="errors"> 
     <li v-for="error in validation.result.errors"> 
      <p :class="error.field + &#39;-&#39; + error.validator">{{error.message}}</p> 
     </li> 
    </ul> 
   </validity-group> 
  </p> 
  <script> 
   new Vue({ 
    data: { 
     validation: { 
      result: {} 
     } 
    }, 
    computed: { 
     requiredErrorMsg: function () { 
      return &#39;Required fruit !!&#39; 
     } 
    }, 
    methods: { 
     handleValidate: function (e) { 
      var $validity = e.target.$validity  
      $validity.validate() 
     } 
    } 
   }).$mount(&#39;#app&#39;) 
  </script> 
 </body> 
</html>

大家学会了吗?赶紧动手尝试一下吧。

相关推荐:

jquery表单验证插件

JavaScript实现表单验证功能的简单示例

纯JavaScript实现基础表单验证的示例代码

以上是详解vue和vue-validator实现表单验证功能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn