Skip to content

Commit ddb94cf

Browse files
committed
reject partial submission if validation fails
If any of the forms to be submitted partially does not validate, then report that form and do not send any data to the server. This action can be bypassed by setting forceSubmission.
1 parent badf529 commit ddb94cf

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

client/django-formset/DjangoFormset.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import isString from 'lodash.isstring';
88
import setDataValue from 'lodash.set';
99
import template from 'lodash.template';
1010
import Sortable, {SortableEvent} from 'sortablejs';
11-
import {StyleHelpers} from './helpers';
11+
import {StyleHelpers, compareArrays} from './helpers';
1212
import {FileUploadWidget} from './FileUploadWidget';
1313
import {ErrorKey, FieldErrorMessages} from './Widget';
1414
import {parse} from '../build/tag-attributes';
@@ -2214,7 +2214,19 @@ export class DjangoFormset implements DjangoFormset {
22142214
async submitPartial(path: Path, extraData?: Object) : Promise<Response|undefined> {
22152215
if (!this.endpoint)
22162216
throw new Error("<django-formset> requires attribute 'endpoint=\"server endpoint\"' for submission");
2217-
this.forms.find(form => isEqual(form.path, path))?.setSubmitted();
2217+
if (!this.forceSubmission) {
2218+
const invalidForms = this.forms.filter(form => {
2219+
if (compareArrays(path, form.path)) {
2220+
form.setSubmitted();
2221+
return !form.isValid();
2222+
}
2223+
});
2224+
if (invalidForms.length > 0) {
2225+
this.clearErrors();
2226+
invalidForms.forEach(form => form.reportValidity());
2227+
return;
2228+
}
2229+
}
22182230
const fullPath = ['formset_data', ...path];
22192231
const extraBody = {_extra: Object.assign({}, this.extraData, extraData)};
22202232
const body = setDataValue(extraBody, fullPath, getDataValue(this.buildBody(), fullPath));

client/django-formset/helpers.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,15 @@ export function asUTCDate(date: Date) : Date {
179179
return new Date(date.getTime() - date.getTimezoneOffset() * 60000);
180180
}
181181

182+
export function compareArrays(needle: Array<string>, haystack: Array<string>): boolean {
183+
for (let k = 0; k < needle.length; k++) {
184+
if (haystack.length <= k || needle[k] !== haystack[k]) {
185+
return false;
186+
}
187+
}
188+
return true;
189+
}
190+
182191
export function assert(condition: any, message?: string) {
183192
if (!condition) {
184193
message = message ? `Assertion failed: ${message}` : "Assertion failed";

0 commit comments

Comments
 (0)