React Native post請求參數校驗組件(Validator)

React Native post請求參數校驗組件(Validator)

在平時開發表單頁面時,常常須要各類參數的校驗,校驗經過發送表單請求,校驗出錯就Toast 錯誤信息,當一個表單有三五項時,咱們作一些if else 判斷還好,當表單項多達10來項,作判斷會增長不少垃圾代碼,並且可維護性也不高,這時咱們能夠封裝一個表單參數校驗組件Valudator來解決這繁瑣的問題。git

效果圖

image

核心源碼

Validator校驗器github

// 登陸表單校驗
const loginValidator = () => ({
  validator: {
    data: ValidateUtil([
      {
        func: (params, state, payload) => Required(params.name), msg: '請輸入用戶名'
      },
      {
        func: (params, state, payload) => Required(params.pwd), msg: '請輸入密碼'
      }
    ])
  }
})

// 註冊表單校驗
const registerValidator = () => ({
  validator: {
    data: ValidateUtil([
      {
        func: (params, state, payload) => Required(params.name), msg: '請輸入手機號'
      },
      {
        func: (params, state, payload) => RegExpr.checkMobile(params.name), msg: '手機號格式不正確'
      },
      {
        func: (params, state, payload) => Required(params.code), msg: '請輸入驗證碼'
      },
      {
        func: (params, state, payload) => Required(params.pwd), msg: '請輸入密碼'
      }
    ])
  }
})
複製代碼

Validator中間件promise

/**
 * Created by guangqiang on 2017/11/23.
 */
import {Toast, deepClone} from '../utils'
export default validatorMiddleware = extraArgument => {

  return ({getState, dispatch}) => next => action => {

    // console.log('action:', action)

    let actionObj = action || {}
    let payloadObj = actionObj.payload
    let metaObj = action.meta || {}
    let validatorObj = metaObj.validator || {}

    if (!metaObj.validator) {
      return next(action)
    }

    let nextAction = undefined
    let nextPayload = undefined

    try {
      nextPayload = action.payload.nextPayload
    } catch (e) {
      return next(action)
    }

    if (nextPayload !== undefined) {
      nextAction = deepClone(action)
      nextAction.payload = nextPayload
    }

    if (metaObj && (typeof nextPayload.promise === 'function') && validatorObj) {

      if (Array.prototype.isPrototypeOf(validatorObj.data) && validatorObj.data.length > 0) {

        let paramsArr = validatorObj.data || []
        let func = null
        let msg = ''
        let isPassed = true
        let params = payloadObj.params || {}
        for (let i = 0; i < paramsArr.length; i ++) {

          let item = paramsArr[i]
          func = item.func
          msg = item.msg

          if(typeof func === 'function') {
            if (typeof func(params, getState(), payloadObj) !== 'boolean') {
              throw new Error('validator func must return boolean type')
            } else {
              if (!func(params, getState(), payloadObj)) {
                Toast.showWarning(msg)
                isPassed = false
                return {
                  err: 'validator',
                  msg: msg,
                  params: params,
                  id: i,
                }
              } else {
                continue
              }
            }
          } else {
            throw new Error('validator func is needed')
          }
        }

        if (isPassed) {
          action = nextAction || action
          if (typeof action.payload.promise === 'function') {
            let promise = action.payload.promise()
            action = {
              ...action,
              payload: {
                ...action.payload,
                promise: promise,
              }
            }
          }
          return next(action)
        }
      }
    }
  }
}
複製代碼

調用方式

submit() {
    let params = {}
    params.name = this.state.mobileNum
    params.code = this.state.verifyCode
    params.pwd = this.state.pwd

    params.iconurl = 'http://ovyjkveav.bkt.clouddn.com/17-11-9/48949929.jpg'
    params.gender = this.state.sex ? this.state.sex : '未知'
    params.province = '上海'
    params.city = '靜安'

    let action = this.props.mockRegister(params)
    if (action instanceof Promise) {
      storage.save('userInfo', params)
      this.props.callback && this.props.callback('register')
      Toast.showSuccess('註冊成功', () => Actions.pop())
    }
  }
複製代碼

從上面的調用方式咱們能夠看到,咱們沒有作任何參數的校驗邏輯處理,這樣使得頁面控制器的js文件顯得極爲的乾淨,沒有過多冗餘的代碼摻雜其中。bash

Validator詳細使用方式請參照項目源碼OneM

github.com/guangqiang-…框架

更多文章

  • 做者React Native開源項目OneM【500+ star】地址(按照企業開發標準搭建框架完成開發的):github.com/guangqiang-…:歡迎小夥伴們 star
  • 做者簡書主頁:包含60多篇RN開發相關的技術文章www.jianshu.com/u/023338566… 歡迎小夥伴們:多多關注多多點贊
  • 做者React Native QQ技術交流羣:620792950 歡迎小夥伴進羣交流學習
  • 友情提示:在開發中有遇到RN相關的技術問題,歡迎小夥伴加入交流羣(620792950),在羣裏提問、互相交流學習。交流羣也按期更新最新的RN學習資料給你們,謝謝你們支持!

小夥伴們掃下方二維碼加入RN技術交流QQ羣

QQ羣二維碼,500+ RN工程師在等你加入哦
相關文章
相關標籤/搜索