Created
October 15, 2019 11:46
-
-
Save IvanofSA/ad5d08bd3042a1364005d988a2febf47 to your computer and use it in GitHub Desktop.
validate
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 Validator from './modules/module.validate' | |
let validator = new Validator({ | |
fields: { | |
current: { | |
empty: { | |
message: 'Поле обязательно к заполнению' | |
} | |
}, | |
checkbox: { | |
unchecked: { | |
message: 'Необходимо подтвердить согласие' | |
} | |
}, | |
phone: { | |
empty: { | |
message: 'Поле обязательно к заполнению' | |
}, | |
pattern: [ | |
{ | |
regex: /^(\+7|7|8)?[\s\-]?\([0-9]{3}\)?[\s\-]?[0-9]{3}[\s\-]?[0-9]{2}[\s\-]?[0-9]{2}$/i, | |
message: 'Проверьте корректность телефона' | |
} | |
] | |
}, | |
name: { | |
empty: { | |
message: 'Поле обязательно к заполнению' | |
}, | |
pattern: [ | |
{ | |
regex: /^[А-Яа-я\-_./\s]*$/, | |
message: 'Проверьте корректность имени' | |
} | |
] | |
}, | |
theme: { | |
empty: { | |
message: 'Поле обязательно к заполнению' | |
}, | |
pattern: [ | |
{ | |
regex: /^[А-Яа-я\-_./\s]*$/, | |
message: 'Проверьте корректность темы' | |
} | |
] | |
}, | |
email: { | |
empty: { | |
message: 'Поле обязательно к заполнению' | |
}, | |
value: [ | |
{ | |
val: 'test@test.test', | |
message: 'Проверьте корректность почты' | |
} | |
], | |
pattern: [ | |
{ | |
regex: /^[-._a-z0-9а-я]+@(?:[a-z0-9а-я][-a-z0-9а-я]+\.)+[a-zа-я]{2,6}$/i, | |
message: 'Проверьте корректность E-mail' | |
} | |
] | |
}, | |
} | |
}); | |
$item.each(function () { | |
let input = $(this), rule = $(this).attr('data-require'); | |
if(!input.is(':visible')) return false; | |
if(rule) { | |
validator.validate(input[0], rule, err => { | |
let $input = $(input[0]), | |
$group = $input.parents('.form__group'), | |
$msg = $group.find('.form__msg'); | |
if(err.errors.length) { | |
wrong = true; | |
$input.addClass('err'); | |
$msg.removeClass('hide'); | |
$msg.addClass('show'); | |
$msg.text(err.errors[0]) | |
} else { | |
$input.removeClass('err'); | |
$msg.removeClass('show'); | |
$msg.addClass('hide'); | |
$msg.text(''); | |
} | |
}) | |
} | |
}); |
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
'use strict'; | |
/** | |
* rules: | |
* | |
* empty - value is empty | |
* unchecked - radio or checkbox is unchecked | |
* aqual - value id | |
* | |
* | |
*/ | |
/** | |
* | |
$('.form').on('submit', function (e) { | |
let $form = $(this), | |
formName = $form.attr('data-form'), | |
$item = $form.find('input, textarea').filter(function(){return $(this).is(':visible')}), | |
wrong = false | |
; | |
$item.each(function () { | |
let input = $(this), rule = $(this).attr('data-require'); | |
if ( !input.is(':visible') ) return false; | |
if ( rule ){ | |
form.validate(input[0], rule, err =>{ | |
if (err.errors.length) { | |
wrong = true; | |
let data = [{ | |
name: input[0].name, | |
error: true, | |
message: err.errors[0] | |
}]; | |
form.result(data); | |
} | |
}) | |
} | |
}); | |
if ( wrong ){ | |
e.preventDefault(); | |
// validate is false | |
} else { | |
// validate is true | |
} | |
}); | |
*/ | |
export default class Form { | |
constructor(options){ | |
this._polyfill(); | |
Object.assign(this._options = {}, this._default(), options); | |
} | |
_polyfill() { | |
String.prototype.strReverse = function() { | |
var newstring = ""; | |
for (var s = 0; s < this.length; s++) { | |
newstring = this.charAt(s) + newstring; | |
} | |
return newstring; | |
}; | |
//assign | |
if (typeof Object.assign !== 'function') { | |
Object.assign = function (target, varArgs) { // .length of function is 2 | |
'use strict'; | |
if (target === null) { // TypeError if undefined or null | |
throw new TypeError('Cannot convert undefined or null to object'); | |
} | |
var to = Object(target); | |
for (var index = 1; index < arguments.length; index++) { | |
var nextSource = arguments[index]; | |
if (nextSource !== null) { // Skip over if undefined or null | |
for (var nextKey in nextSource) { | |
// Avoid bugs when hasOwnProperty is shadowed | |
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { | |
to[nextKey] = nextSource[nextKey]; | |
} | |
} | |
} | |
} | |
return to; | |
}; | |
} | |
} | |
_default() { | |
return { | |
fields: { | |
current: { | |
empty: { | |
message: 'Заполните поле' | |
} | |
}, | |
radio: { | |
unchecked: { | |
message: 'Отметьте один из вариантов' | |
} | |
}, | |
checkbox: { | |
unchecked: { | |
message: 'Для продолжения нужно подтверждение' | |
} | |
}, | |
select: { | |
empty: { | |
message: 'Выберите один из вариантов' | |
} | |
}, | |
email: { | |
empty: { | |
message: 'Заполните поле' | |
}, | |
value: [ | |
{ | |
val: 'test@test.test', | |
message: 'Какая, оригинальная почта...' | |
} | |
], | |
pattern: [ | |
{ | |
regex: /^[-._a-z0-9а-я]+@(?:[a-z0-9а-я][-a-z0-9а-я]+\.)+[a-zа-я]{2,6}$/i, | |
message: 'Проверьте корректность E-mail' | |
} | |
], | |
// antiPattern: [ | |
// { | |
// regex: 'test@test.test', | |
// message: 'Какая, блин, оригинальная почта...' | |
// } | |
// ] | |
}, | |
password: { | |
empty: { | |
message: 'Заполните поле' | |
}, | |
pattern: [ | |
{ | |
regex: /[a-z]/i, | |
message: 'Используйте строчные символы' | |
}, | |
{ | |
regex: /[A-Z]/i, | |
message: 'Используйте заглавные символы' | |
}, | |
{ | |
regex: /[0-9]/i, | |
message: 'Используйте цифры' | |
}, | |
{ | |
regex: /\W/i, | |
message: 'Используйте спецсимволы' | |
} | |
], | |
antiPattern: [ | |
{ | |
regex: /[а-я]/i, | |
message: 'Кирилические символы недопустимы в пароле' | |
}, | |
{ | |
regex: /\s/i, | |
message: 'Нельзя использовать пробел' | |
} | |
], | |
min:{ | |
length: 6, | |
message: 'Длина пароля должна быть не менее 6 символов' | |
}, | |
max: { | |
length: 999, | |
message: 'Длина пароля не должна превышать 999 символов' | |
}, | |
}, | |
number: { | |
empty: { | |
message: 'Заполните поле' | |
}, | |
pattern: [ | |
{ | |
regex: /^\d+$/i, | |
message: 'Поле должно содержать только числовые символы' | |
} | |
], | |
} | |
} | |
} | |
} | |
validate(input, type, callback) { | |
if ( !type || type === 'true' || type === true ) { | |
if ( input.type === 'radio' | |
|| input.type === 'checkbox' | |
|| input.type === 'email' | |
// || input.type === 'password' | |
){ | |
type = input.type; | |
} else { | |
type = 'current'; | |
} | |
} | |
let err = [], val, m = type.match(/\[(.*)?\]/), selector; | |
val = input.value.trim(); | |
if (m && m.length > 1){ | |
selector = type; | |
type = '_link'; | |
} | |
let rules = this._options.fields[type]; | |
if ( !!rules ){ | |
for (let rule in rules) { | |
if (rules.hasOwnProperty(rule)) { | |
switch (rule){ | |
case 'empty': | |
if ( val === '' ) err.push(rules[rule].message); | |
break; | |
case 'aqual': | |
if ( val !== rules[rule].value(selector) ) err.push(rules[rule].message); | |
break; | |
case 'pattern': | |
if ( rules[rule].length ) rules[rule].map(item=>{ | |
if ( item.regex && item.regex instanceof RegExp && !item.regex.test(val) ) err.push(item.message); | |
}); | |
break; | |
case 'antiPattern': | |
if ( rules[rule].length ) rules[rule].map(item=>{ | |
if ( item.regex && item.regex instanceof RegExp && item.regex.test(val) ) { | |
err.push(item.message); | |
} else if ( item.regex && typeof item.regex === 'string' && val === item.regex ){ | |
err.push(item.message); | |
} | |
}); | |
break; | |
case 'min': | |
if ( val.length < rules[rule].length ) err.push(rules[rule].message); | |
break; | |
case 'max': | |
if ( val.length > rules[rule].length ) err.push(rules[rule].message); | |
break; | |
case 'unchecked': | |
if ( input.type === 'radio' ){ | |
let i = 0, radio = document.querySelectorAll(`input[name="${input.name}"]`), checked = false; | |
for (i; i < radio.length; i++ ){ | |
if ( radio[i].checked ) { | |
checked = true; | |
break; | |
} | |
} | |
if ( !checked ) err.push(rules[rule].message); | |
} else if ( !input.checked ) { | |
err.push(rules[rule].message); | |
} | |
break; | |
default: | |
} | |
} | |
} | |
} | |
if (callback && typeof callback === 'function') callback({errors: err, value: val, type: type}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment