From e609aea4b680ed05d949852891145412f4633e97 Mon Sep 17 00:00:00 2001 From: Faris Ansari Date: Fri, 27 Dec 2019 15:55:23 +0530 Subject: [PATCH] feat: Standard validations for email and phone --- model/document.js | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/model/document.js b/model/document.js index d54b6f5c..cc4c07ed 100644 --- a/model/document.js +++ b/model/document.js @@ -237,10 +237,38 @@ module.exports = class BaseDocument extends Observable { this.meta.validateSelect(field, value); } if (field.validate) { - await field.validate(value, this); + let validator = null; + if (typeof field.validate === 'object') { + validator = this.getValidateFunction(field.validate); + } + if (typeof field.validate === 'function') { + validator = field.validate; + } + if (validator) { + await validator(value, this); + } } } + getValidateFunction(validator) { + let functions = { + email(value) { + let isValid = /(.+)@(.+){2,}\.(.+){2,}/.test(value); + if (!isValid) { + throw new frappe.errors.ValidationError(`Invalid email: ${value}`); + } + }, + phone(value) { + let isValid = /[+]{0,1}[\d ]+/.test(value); + if (!isValid) { + throw new frappe.errors.ValidationError(`Invalid phone: ${value}`); + } + } + }; + + return functions[validator.type]; + } + getValidDict() { let data = {}; for (let field of this.meta.getValidFields()) {