React Native post請求參數(shù)校驗(yàn)組件(Validator)
在平時(shí)開發(fā)表單頁面時(shí),經(jīng)常需要各種參數(shù)的校驗(yàn)忙干,校驗(yàn)通過發(fā)送表單請求器予,校驗(yàn)出錯就Toast 錯誤信息,當(dāng)一個(gè)表單有三五項(xiàng)時(shí)捐迫,我們做一些if else
判斷還好乾翔,當(dāng)表單項(xiàng)多達(dá)10來項(xiàng),做判斷會增加很多垃圾代碼施戴,而且可維護(hù)性也不高反浓,這時(shí)我們可以封裝一個(gè)表單參數(shù)校驗(yàn)組件Valudator來解決這繁瑣的問題。
效果圖
核心源碼
Validator校驗(yàn)器
// 登錄表單校驗(yàn)
const loginValidator = () => ({
validator: {
data: ValidateUtil([
{
func: (params, state, payload) => Required(params.name), msg: '請輸入用戶名'
},
{
func: (params, state, payload) => Required(params.pwd), msg: '請輸入密碼'
}
])
}
})
// 注冊表單校驗(yàn)
const registerValidator = () => ({
validator: {
data: ValidateUtil([
{
func: (params, state, payload) => Required(params.name), msg: '請輸入手機(jī)號'
},
{
func: (params, state, payload) => RegExpr.checkMobile(params.name), msg: '手機(jī)號格式不正確'
},
{
func: (params, state, payload) => Required(params.code), msg: '請輸入驗(yàn)證碼'
},
{
func: (params, state, payload) => Required(params.pwd), msg: '請輸入密碼'
}
])
}
})
Validator中間件
/**
* 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)
}
}
}
}
}
調(diào)用方式
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())
}
}
從上面的調(diào)用方式我們可以看到赞哗,我們沒有做任何參數(shù)的校驗(yàn)邏輯處理雷则,這樣使得頁面控制器的js文件顯得極為的干凈,沒有過多冗余的代碼摻雜其中肪笋。
Validator詳細(xì)使用方式請參照項(xiàng)目源碼OneM
https://github.com/guangqiang-liu/OneM
更多文章
- 作者React Native開源項(xiàng)目OneM【500+ star】地址(按照企業(yè)開發(fā)標(biāo)準(zhǔn)搭建框架完成開發(fā)的):https://github.com/guangqiang-liu/OneM:歡迎小伙伴們 star
- 作者簡書主頁:包含60多篇RN開發(fā)相關(guān)的技術(shù)文章http://www.reibang.com/u/023338566ca5 歡迎小伙伴們:多多關(guān)注月劈,多多點(diǎn)贊