Skip to content

Commit e08dbbb

Browse files
committed
Allow form fields required state to be controlled with a function,
just like it's already possible with "visible" and "disabled"
1 parent ea91365 commit e08dbbb

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/formGenerator.vue

+12-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ div
108108
disabled: this.fieldDisabled(field),
109109
readonly: field.readonly,
110110
featured: field.featured,
111-
required: field.required
111+
required: this.fieldRequired(field)
112112
};
113113
114114
if (isArray(field.styleClasses)) {
@@ -139,6 +139,17 @@ div
139139
return field.disabled;
140140
},
141141
142+
// Get required prop of field
143+
fieldRequired(field) {
144+
if (isFunction(field.required))
145+
return field.required(this.model);
146+
147+
if (isNil(field.required))
148+
return false;
149+
150+
return field.required;
151+
},
152+
142153
// Get visible prop of field
143154
fieldVisible(field) {
144155
if (isFunction(field.visible))

test/unit/specs/VueFormGenerator.spec.js

+35
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,41 @@ describe("VueFormGenerator.vue", () => {
306306

307307
});
308308

309+
describe("check fieldRequired with function", () => {
310+
let schema = {
311+
fields: [
312+
{
313+
type: "text",
314+
label: "Name",
315+
model: "name",
316+
required(model) { return model.status; }
317+
}
318+
]
319+
};
320+
321+
let model = {
322+
name: "John Doe",
323+
status: true
324+
};
325+
326+
before( () => {
327+
createFormGenerator(schema, model);
328+
});
329+
330+
it("should be required", () => {
331+
expect(el.querySelector(".form-group").classList.contains("required")).to.be.true;
332+
});
333+
334+
it("should be optional", (done) => {
335+
model.status = false;
336+
vm.$nextTick(() => {
337+
expect(el.querySelector(".form-group").classList.contains("required")).to.be.false;
338+
done();
339+
});
340+
});
341+
342+
});
343+
309344
describe("check fieldVisible with function", () => {
310345
let schema = {
311346
fields: [

0 commit comments

Comments
 (0)