-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (59 loc) · 2.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const T = require('./lib/type.js')
const InvalidMessages = require('./lib/language.js')
const Rules = require('./lib/rules.js')
const get = require('lodash.get')
function validateSingleParamByMultipleRules (name, val, rulesString, allRules, allInvalidMsg, allParams) {
let result = ''
const rules = rulesString.split('|')
for (let i = 0, len = rules.length; i < len; i++) {
const rule = rules[i]
const idxOfSeparator = rule.indexOf(':')
let ruleName = rule
let ruleValue = ''
if (~idxOfSeparator) {
ruleValue = rule.substr(idxOfSeparator + 1)
ruleName = rule.substr(0, idxOfSeparator)
}
const fn = allInvalidMsg[ruleName + '']
if (!allRules[ruleName](val, ruleValue, allParams)) {
result = {
paramName: name,
actualValue: val,
invalidMessage: fn(name, val, ruleValue)
}
break
}
}
return result
}
/**
*
* return first invalid param info by default
* you can set inDepth true, get all invalid params info
* return chinese invalid message by default
* you can set lang 'en', get English invalid message
*
*/
function main (params, schema, options = {}) {
const invalidParams = []
if (!T.isObject(schema)) return invalidParams
if (!T.isObject(params)) params = {}
const needValidateParamNameList = Object.keys(schema)
if (!needValidateParamNameList.length) return invalidParams
const { language = 'zh', deep = false, extRules = {}, extInvalidMessages = {} } = options
const allRules = Object.assign({}, Rules, extRules)
const allInvalidMessages = Object.assign({}, InvalidMessages[language], extInvalidMessages)
for (let i = 0, len = needValidateParamNameList.length; i < len; i++) {
const name = needValidateParamNameList[i]
const val = get(params, name)
const rulesString = schema[name]
if (!name || !rulesString || (T.isUndefined(val) && !rulesString.includes('required'))) continue
const invalidInfo = validateSingleParamByMultipleRules(name, val, rulesString, allRules, allInvalidMessages, params)
if (invalidInfo) {
invalidParams.push(invalidInfo)
if (!deep) break
}
}
return invalidParams
}
module.exports = main