// validation patterns
const fname = /^[a-z ]{5,}$/i;
const sname = /^[a-z ]{5,}$/i;
const email = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
const phone = /^\+7[0-9]{10}$/;
const patterns = {
name: fname,
surname: sname,
email,
phone,
mobilePhone: phone,
workPhone: phone
};
// forms
const forms = [
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690' },
{ name: 'III', email: 'ivan@test', phone: '11111' },
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: '+79212753690'},
{},
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: 'фывыафывафыв'},
{ name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', mobilePhone: '+79212753690', workPhone: 'asfdadsfd', surname: ''},
{ surname: 'Ivan Ivanov', mobilePhone: 'фывафыва', name: 'Ivan Ivanov', email: 'ivan@test.co', phone: '+79212753690', workPhone: '+79212753690'
}
];
validateAll(forms, patterns);
function validateAll(forms, patterns) {
return forms.map( form => validate(form, patterns) );
}
function validate(form, patterns) {
const keys = Object.keys(form);
const errors = [];
if(!keys.length) return {target: {}, errors: ['empty form is provided']};
keys.forEach(key => {
if( !patterns[key].test(form[key]) ) {
errors.push(`${key} value is invalid`);
}
});
return {
target: JSON.stringify(form),
errors
};
}
https://repl.it/IBuo/1