Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Validation = {
- types: {
- require: {
- checker(value, option) {
- return !!value;
- },
- message(option) {
- return `This field is required.`;
- }
- },
- minlength: {
- checker(value, option) {
- return !!value && value.length >= option;
- },
- message(option) {
- return `This field must has at least ${option} letters.`;
- }
- },
- nodigits: {
- checker(value, option) {
- return !/\d/.test(value);
- },
- message(option) {
- return `This field shouldn't contains digits.`;
- }
- },
- isimage: {
- checker(value, option) {
- console.log(value);
- console.log(/\.(jpe?g|png|gif|svg)$/i.test(value));
- return /\.(jpe?g|png|gif|svg)$/i.test(value);
- },
- message(option) {
- return `This file isn't an image.`
- }
- },
- email: {
- checker(value, option) {
- return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
- },
- message(option) {
- return `This field doesn't match with appropriate pattern`;
- }
- }
- },
- errors: {},
- validate(config, values) {
- let checker = null, // username, email, pass, ...
- message = null, // function
- checkers = null, // require, minlength
- option = null; // true, 3
- // clear existing errors
- this.errors = {};
- if (!config) throw 'You have to pass a configuration!';
- for (let key in config) {
- checkers = ( config[key] ) ? Object.keys( config[key] ) : [];
- // validation
- for (let i = 0; i < checkers.length; i++) {
- let item = checkers[i];
- checker = this.types[item].checker;
- message = this.types[item].message;
- option = config[key][item];
- // throw an error if the validation method is missed
- if (!checker) {
- throw (`You don't have a validation method for ${checker} option`);
- }
- if ( !checker(values[key], option) ) {
- // add an error into the errors object and
- this.errors[key] = message(option);
- // switch to validation of next value
- break;
- }
- }
- }
- return this.errors;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement