Skip to content

Instantly share code, notes, and snippets.

@heimdallrj
Last active October 26, 2017 11:18
Show Gist options
  • Save heimdallrj/1e390641f310003b8f3ec95f341e0c39 to your computer and use it in GitHub Desktop.
Save heimdallrj/1e390641f310003b8f3ec95f341e0c39 to your computer and use it in GitHub Desktop.
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