@e-group/utils
Version:
eGroup team utils that share across projects.
68 lines (52 loc) • 1.55 kB
JavaScript
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import { isValid, isBefore } from 'date-fns';
import isLength from 'validator/lib/isLength';
import isEmail from 'validator/lib/isEmail';
import isMobilePhone from 'validator/lib/isMobilePhone';
class Validator {
constructor(errors, name, value) {
_defineProperty(this, "errors", void 0);
_defineProperty(this, "name", void 0);
_defineProperty(this, "value", void 0);
this.errors = errors;
this.name = name;
this.value = value;
}
isRequired(message) {
if (!this.value) {
this.errors[this.name] = message;
}
return this;
}
isMobilePhone(message, locale) {
if (this.value && typeof this.value === 'string' && !isMobilePhone(this.value, locale)) {
this.errors[this.name] = message;
}
return this;
}
isEmail(message) {
if (this.value && typeof this.value === 'string' && !isEmail(this.value)) {
this.errors[this.name] = message;
}
return this;
}
lengthLimit(max, message) {
if (this.value && !isLength(String(this.value), {
min: 0,
max
})) {
this.errors[this.name] = message;
}
return this;
}
isDateBefore(date, message) {
if (this.value && typeof this.value !== 'string' && isValid(this.value) && isBefore(this.value, date)) {
this.errors[this.name] = message;
}
return this;
}
}
export default function factory(errors, name, value) {
const validator = new Validator(errors, name, value);
return validator;
}