background
Many UI frameworks on the market now have form validation, as well as tripartite libraries. My application scenario does not need to be tied to the UI, traditional commit validation – one by one, in order.
🌰
For example, IF I have an interface parameter params1, params2 needs to be checked and is not null.
The traditional way is of course the fastest if else
if(! paramsN) { alter(msgN) return false }Copy the code
The strategy pattern
Since I read the article related to the strategy mode, I was inspired by it. At the same time, I moved the custom validator written by the big guy and realized it through proxy. So let’s take a look at that and how do we encapsulate it
Export const validatorCreater = (target, validator) => new Proxy(target, {// Save the _validator: Validator, set (target, key, value, receiver) {// If the assigned attribute has a validator, If (this._validator[key]) {for (let validatorStrategy of this._validator[key]) {let {errorMsg = ", params = []} = validatorStrategy if (! validatorStrategy.validator.call(null, value, ... Params)) {throw new Error(errorMsg)}}} Return reflect. set(target, key, value, receiver)}})Copy the code
How to use
_checkValue = ({ parentId, Const isNotEmpty = val => val && (val + ''). Length > 0 const objEmpty = val =>! _.isEmpty(val) let validators = { baseInfo: [{ validator: objEmpty, errorMsg: 'xxxx' }], parentId: [{ validator: isNotEmpty, errorMsg: 'xxxx' }] } const checkObj = validatorCreater({}, validators) try { checkObj.parentId = parentId checkObj.baseInfo = baseInfo } catch (e) { console.warn(e) message.error(e.message) return false } return true }Copy the code
How about that? I think it paid off. After a period of time, I thought about whether A simple version could be realized through ES5. After careful consideration, I came up with a prototype scheme as follows
Lite version
export const checkParams = (rules = []) => callback => { let checkStatus = true try { for (let i = 0; i < rules.length; i++) { const { fn, value, errorMsg } = rules[i] if (! fn(value)) { checkStatus = false callback && callback(errorMsg) break } } } catch (error) { console.error(error) Console. warn(' Value type ------ fn: check function value: required check value errorMsg: error message ')} return checkStatus}Copy the code
Outside calls
_checkParams = ({ inquiryPrice, inquiryUnit, sellStockNum }) = > {
const isNotEmpty = val= > val && (val + ' ').length > 0
const rules = [
{ fn: isNotEmpty, value: inquiryPrice, errorMsg: 'Please fill in 1' },
{ fn: isNotEmpty, value: inquiryUnit, errorMsg: 'Please select 2' },
{ fn: isNotEmpty, value: sellStockNum, errorMsg: 'please fill in the 3'}]return checkParams(rules)(message.error)
}
Copy the code
To improve the
Empty and regular are the most commonly used functions, which can be optimized as follows
const _ = require('lodash') export default (rules = []) => callback => { let checkStatus = true try { for (let i = 0; i < rules.length; I ++) {const {fn, value, errorMsg = 'This parameter is invalid ', Required, pattern} = rules[I] // only null if (required &&! IsEmpty (value)) {checkStatus = false callback && callback(errorMsg) break isEmpty(value) && ! patternCheck(pattern, Value) {checkStatus = false callback && callback(errorMsg) break} fn(value)) { checkStatus = false callback && callback(errorMsg) break } } } catch (error) { console.error(error) Console. warn(' Owning value type ------ fn: user-defined verification function value: required verification value errorMsg: error message, required: Mandatory, pattern: Regular ')} return checkStatus} const isEmpty = (value) => {const types = ['string', 'number'] const isExit = types.includes(typeof value) if (isExit) { return (value + '').length > 0 } else { if (! Value) {return null, undefined return false} else {return! _.isEmpty(value) } } } const patternCheck = (reg, Value) => {if ((typeof value) === 'string') {return reg.test(value)} else {console.warn(' re only valid for string') return false }}Copy the code
use
const rules = [
{ value: 1.required: true},
{ value: - 1.fn: (val) = > val > 0.pattern: /^\d{1,}$/ },
{ value: - 1.fn: (val) = > val > 0 }
]
checkParams(rules)(console)
Copy the code