首頁 >web前端 >js教程 >vue、vue-validator實作表單驗證功能

vue、vue-validator實作表單驗證功能

小云云
小云云原創
2018-05-14 16:15:151950瀏覽

本文主要介紹vue+vue-validator 表單驗證功能的實作程式碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下,希望能幫助到大家。

官方文件:http://vuejs.github.io/vue-validator/zh-cn/index.html

github專案網址:https://github.com /vuejs/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>

相關推薦:

Bootstrap表單驗證功能詳解

layui.js實作的表單驗證功能範例

#JS實作的簡單表單驗證功能範例

以上是vue、vue-validator實作表單驗證功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn