Last active
September 11, 2018 10:35
-
-
Save taburetkin/ef94ae2c59981ac04ab0f54d5c2a190e to your computer and use it in GitHub Desktop.
validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getAjax from 'helpers/get-ajax'; | |
export function normalizeValidateRules(rules){ | |
return _.reduce(rules, (memo, value, key) => { | |
memo[key] = normalizeValidationContext(value); | |
return memo; | |
}, {}); | |
} | |
export function normalizeValidationContext(context){ | |
if (context === 'required') { | |
return { required: true }; | |
} else if(_.isFunction(context)) { | |
return { validate: context }; | |
} else if(_.isObject(context)) { | |
return context; | |
} | |
} | |
export function validateItem(value, rule, opts = {}) | |
{ | |
rule = normalizeValidationContext(rule); | |
let { | |
required, requiredMessage, type, | |
valueIn, valueInMessage, | |
valueNotIn, valueNotInMessage, | |
minValue, minValueMessage, | |
maxValue, maxValueMessage, | |
minLength, minLengthMessage, | |
maxLength, maxLengthMessage, | |
pattern, patternMessage, | |
shouldBeEqual, shouldBeEqualMessage, | |
apiIsUnique | |
} = rule; | |
let { valuesHash = {}, fullValue } = opts; | |
if(_.isObject(fullValue)){ | |
valuesHash = fullValue; | |
} | |
let errors = []; | |
if( apiIsUnique ) { | |
let cleanRule = _.omit(rule, 'apiIsUnique', 'apiIsUniqueMessage'); | |
return validateItem(value, cleanRule, errors).then(() => { | |
return requestApi(value, rule, errors); | |
}); | |
} | |
//const textTypes = ['text','string','password']; | |
return new Promise((resolve, reject) => { | |
if (!required && (value == null || value === '')) { | |
resolve(); | |
return; | |
}else if(required && (value == null || value === '')) { | |
errors.push(requiredMessage || 'это обязательное поле'); | |
value = ''; | |
} | |
if(type === 'email'){ | |
email(value, rule, errors); | |
} | |
// else if(type && textTypes.indexOf() type != 'text' && type != 'string' && (typeof value != type)) { | |
// errors.push(typeMessage || 'несоответствие типа:' + type); | |
// } | |
if(_.isArray(valueIn)) { | |
if(valueIn.indexOf(value) == -1) | |
errors.push(valueInMessage || 'значение не входит в разрешенные'); | |
} | |
if(_.isArray(valueNotIn)) { | |
if(valueNotIn.indexOf(value) !== -1) | |
errors.push(valueNotInMessage || 'значение входит в запрещённые'); | |
} | |
if (shouldBeEqual) { | |
let checkValue = shouldBeEqual; | |
if(_.isFunction(shouldBeEqual)) { | |
checkValue = shouldBeEqual(valuesHash || {}); | |
} | |
if (value != checkValue) { | |
errors.push(shouldBeEqualMessage || 'значение не совпадает'); | |
} | |
} | |
if (_.isNumber(minLength)) { | |
if(value.toString().length < minLength) | |
errors.push(minLengthMessage || `минимальная длина: ${minLength}`); | |
} | |
if (_.isNumber(maxLength)) { | |
if(value.toString().length > maxLength) | |
errors.push(maxLengthMessage || `максимальная длина: ${maxLength}`); | |
} | |
if(minValue) | |
{ | |
if(value < minValue) | |
errors.push(minValueMessage || `минимальное значение: ${minValue}`); | |
} | |
if(maxValue) | |
{ | |
if(value > maxValue) | |
errors.push(maxValueMessage || `максимальное значение: ${maxValue}`); | |
} | |
if (pattern) { | |
!_.isRegExp(pattern) && (pattern = new RegExp(pattern)); | |
if(!pattern.test(value)) { | |
errors.push(patternMessage || 'значение не соответствует шаблону'); | |
} | |
} | |
if (errors.length) { | |
reject(errors); | |
} else { | |
resolve(); | |
} | |
}); | |
} | |
function email(email, { emailMessage }, errors = []) { | |
!_.isString(email) && (email = (email || '').toString()); | |
let chunks = email.split('@'); | |
let left = chunks[0]; | |
let right = chunks[1]; | |
if( | |
chunks.length != 2 | |
|| !/^[a-z0-9\-_.+]+$/gmi.test(left) | |
|| !/^[a-z0-9\-_]+\.[a-z0-9\-_]+(\.[a-z0-9\-_]+)*$/gmi.test(right) | |
) { | |
errors.push(emailMessage || 'не соответствует формату email'); | |
return errors; | |
} else { | |
return; | |
} | |
} | |
function requestApi(value, { apiIsUnique, apiIsUniqueMessage }, errors = []){ | |
if(value == null || value === ''){ | |
return Promise.resolve(); | |
} | |
const ajax = getAjax(); | |
return new Promise((resolve, reject) => { | |
ajax({ | |
url: apiIsUnique + '?value=' + encodeURIComponent(value), | |
method: 'GET', | |
}).then( | |
(data) => { | |
if(data != null){ | |
errors.push(apiIsUniqueMessage || 'это значение уже используется'); | |
reject(errors); | |
} else { | |
resolve(value); | |
} | |
}, | |
() => { | |
errors.push(apiIsUniqueMessage || 'это значение уже используется'); | |
reject(errors); | |
} | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment