React Native post请求参数校验组件(Validator)
在平时开发表单页面时,经常需要各种参数的校验,校验通过发送表单请求,校验出错就Toast 错误信息,当一个表单有三五项时,我们做一些if else
判断还好,当表单项多达10来项,做判断会增加很多垃圾代码,而且可维护性也不高,这时我们可以封装一个表单参数校验组件Valudator来解决这繁琐的问题。
效果图
核心源码
Validator校验器
// 登录表单校验
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中间件
/**
* 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文件显得极为的干净,没有过多冗余的代码掺杂其中。
Validator详细使用方式请参照项目源码OneM
https://github.com/guangqiang-liu/OneM
更多文章
- 作者React Native开源项目OneM【500+ star】地址(按照企业开发标准搭建框架完成开发的):https://github.com/guangqiang-liu/OneM:欢迎小伙伴们 star
- 作者简书主页:包含60多篇RN开发相关的技术文章http://www.jianshu.com/u/023338566ca5 欢迎小伙伴们:多多关注,多多点赞