From 7af5c30e7bc0bd4bfdc4c0e1625ab9fad3bb9d44 Mon Sep 17 00:00:00 2001 From: Faris Ansari Date: Thu, 5 Dec 2019 00:13:08 +0530 Subject: [PATCH] fix: validateMandatory in insert --- common/errors.js | 8 ++++++++ model/document.js | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/common/errors.js b/common/errors.js index 876e807a..d2e52fc0 100644 --- a/common/errors.js +++ b/common/errors.js @@ -44,6 +44,13 @@ class LinkValidationError extends ValidationError { } } +class MandatoryError extends ValidationError { + constructor(message) { + super(message); + this.name = 'MandatoryError'; + } +} + class DatabaseError extends BaseError { constructor(message) { super(500, message); @@ -79,5 +86,6 @@ module.exports = { DuplicateEntryError, LinkValidationError, DatabaseError, + MandatoryError, throw: throwError }; diff --git a/model/document.js b/model/document.js index f8ad924f..8e4b3a44 100644 --- a/model/document.js +++ b/model/document.js @@ -166,6 +166,26 @@ module.exports = class BaseDocument extends Observable { } } + validateInsert() { + this.validateMandatory(); + } + + validateMandatory() { + let mandatoryFields = this.meta.fields.filter(df => df.required); + let missingMandatoryFields = mandatoryFields.filter(df => { + let value = this[df.fieldname]; + if (df.fieldtype === 'Table') { + return !value || value.length === 0; + } + return value == null || value === ''; + }); + if (missingMandatoryFields.length > 0) { + let fields = missingMandatoryFields.map(df => `"${df.label}"`).join(', '); + let message = frappe._('Value missing for {0}', fields); + throw new frappe.errors.MandatoryError(message); + } + } + async validateField(key, value) { let field = this.meta.getField(key); if (field && field.fieldtype == 'Select') { @@ -439,6 +459,7 @@ module.exports = class BaseDocument extends Observable { async insert() { await this.setName(); await this.commit(); + await this.validateInsert(); await this.trigger('beforeInsert'); let oldName = this.name;