Skip to content

Instantly share code, notes, and snippets.

@thinkholic

thinkholic/Validator.js

Last active Oct 26, 2017
Embed
What would you like to do?
Validator.js
class Validator {
schema = null;
constructor(schema) {
this.schema = schema;
}
run(values) {
const schema = this.schema;
const errors = {};
const fields = Object.keys(schema);
fields.forEach(field => {
let errorMessage = null;
const attr = schema[field];
let value = values[field];
if (typeof value === "string") {
value = value.trim();
}
if (attr.length) {
const length = String(value).length;
if (length < attr.length.min) {
errorMessage = "The value is too short!";
}
if (length > attr.length.max) {
errorMessage = "The value is too long!";
}
}
// Custom
if (attr.custom) {
errorMessage = this[attr.custom](field, values);
}
// Type
if (attr.type) {
if (typeof value !== attr.type) {
errorMessage = "Invalid data type!";
}
}
// include
if (attr.include && Array.isArray(attr.include)) {
if (!attr.include.includes(value)) {
errorMessage = "Invalid value!";
}
}
// exclude
if (attr.exclude && Array.isArray(attr.exclude)) {
if (attr.exclude.includes(value)) {
errorMessage = "Invalid value!";
}
}
// inBetween
if (attr.inBetween) {
const valueInBetween = value * 1;
if (typeof valueInBetween !== "number" || isNaN(valueInBetween)) {
errorMessage = "Invalid data type!";
} else {
if (attr.inBetween.min && valueInBetween < attr.inBetween.min) {
errorMessage = "Out of range!";
}
if (attr.inBetween.max && valueInBetween > attr.inBetween.max) {
errorMessage = "Out of range!";
}
}
}
if (attr.required) {
if (!value) {
errorMessage = `${attr.name} is required!`;
}
}
if (errorMessage) {
errors[field] = errorMessage;
}
});
return errors;
}
validateEmail(field, allValues) {
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(allValues[field])) {
return "Invalid email address";
}
return false;
}
}
export default Validator;
// Scheme
export const schema = {
someField: {
name: "Field Name",
type: "number",
required: true,
inBetween: {
min: 1.5,
max: null
}
},
:
:
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment