寫一個簡單易用可擴展vue表單驗證插件(vue-validate-easy)

寫一個vue表單驗證插件(vue-validate-easy)

需求

目標:簡單易用可擴展html

如何簡單

開發者要作的

  1. 寫了一個表單,指定一個name,指定其驗證規則。
  2. 調用提交表單方法,能夠獲取驗證成功後的數據。
  3. 調用重置表單方法重置表單
  4. 自定義驗證方法

程序應該作的

  1. 獲取表單元素,綁定事件
  2. 有輸入時,獲取表單值,使用開發者指定的規則進行驗證,若驗證錯誤給予錯誤提示。

實現方法

  • 獲取原生表單元素,vue指令獲取到的是包裹原生表單元素的外層元素,這裏我使用data-type屬性來獲取原生表單元素
  • 驗證規則,驗證參數,自定義錯誤提示語 由 vue的指令值來獲取
  • 提交時,咱們須要一個表單標識,這裏我使用了data-scope屬性來對錶單進行分組
  • 重置,經過data-scope重置整個表單

經常使用方法

  • 懶驗證,經過.lazy指令修飾符
  • 遠程驗證, 經過async await
  • 延時驗證, .deay指令修飾符,和data-delay屬性
  • 表單主動驗證,單字段主動驗證
  • 單字段表單重置

可擴展

  • 錯誤消息自定義
  • 驗證方法自定義
  • 錯誤提示處理自定義
  • 自定義表單元素(不借助原生元素)

完成後的使用代碼

// 你只要指定 data-scope data-name data-type v-validate-easy 這四個屬性的值,而後經過調用this.V.$submit(scope)就能夠進行提交表單了
<form>
    <div class="my-form-group" data-scope="register" data-name="email" data-type="input"
    v-validate-easy="[['required','郵箱爲必填項目'],['email']]">
      <label>
        <div class="label">郵箱</div>
        <input class="input" type="text" spellcheck="false" placeholder="請輸入郵箱"/>
      </label>
    </div>
    
    <div id="pwd" class="my-form-group" data-scope="register" data-name="password" data-type="input"
    v-validate-easy="[['required','密碼不能爲空'],['password'],['maxLength',[32],'密碼最長爲32位']]">
      <label>
        <div class="label">密碼</div>
        <input class="input" type="text" spellcheck="false" placeholder="請再次輸入密碼"/>
      </label>
    </div>
    
    <div class="my-form-group" data-scope="register" data-name="password" data-type="input"
    v-validate-easy="[['required','確認密碼不能爲空'],['equalTo',['pwd'],'密碼輸入不一致']]">
      <label>
        <div class="label">確認密碼</div>
        <input class="input" type="text" spellcheck="false" placeholder="請輸入郵箱"/>
      </label>
    </div>
    <div class="btn-group">
      <button class="my-btn" @click.prevent="submit('register')">註冊</button>
      <button class="my-btn" @click.prevent="reset('register')">重置</button>
    </div>
  </form>
methods: {
    reset(scope) {
      this.V.$reset(scope)
    },
    submit(scope) {
      this.V.$submit(scope, (canSumit,data) => {
        // canSumit爲true時,則全部該scope的全部表單驗證經過
        if(!canSumit) return

        // 發送請求
        axios({ url: '/test',data, method: 'post'})
          .then(() => {
            // 成功響應處理
          })
          .catch(() => {
            // 錯誤處理
          })
      })
    }
  },

對自定義組件使用,就更加簡潔

<form>
    <h3>用戶登陸</h3>
    <my-input label="用戶名" data-scope="login" data-name="username" v-validate-easy="[['required']]"></my-input>
    <my-input label="密碼" data-scope="login" type="password" data-name="pwd" v-validate-easy="[['required']]"></my-input>

    <div class="btn-group">
      <button class="my-btn" @click.prevent="submit('login')">登陸</button>
      <button class="my-btn" @click.prevent="reset('login')">重置</button>
    </div>
  </form>

vue-validate-easy github地址

歡迎你們star,對該項目有什麼問題和建議,歡迎提issuevue

vue-validate-easy 文檔地址

相關文章
相關標籤/搜索