Skip to content

Commit

Permalink
feat: abort form submission when pristine
Browse files Browse the repository at this point in the history
  • Loading branch information
JakobJingleheimer committed Sep 29, 2023
1 parent 89edd5e commit 5097a9a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/react/Form/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ export default memo(Form);
export function onSubmit(event, initValues, cb) {
event.preventDefault();

if (event.target.hasAttribute('pristine')) return;

if (!event.target.reportValidity()) return;

event.stopPropagation();
Expand Down
13 changes: 12 additions & 1 deletion lib/react/Form/Form.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('Form', () => {
let initValues;

function generateFakeSubmissionEvent({
attrs = { pristine: false },
valid = true
} = {}) {
const spies = {
Expand All @@ -28,6 +29,7 @@ describe('Form', () => {
stopPropagation() { spies.stopPropagationCalled = true },
target: {
elements: [],
hasAttribute(name) { return attrs[name] },
reportValidity() {
spies.reportValidityCalled = true;
return valid;
Expand Down Expand Up @@ -65,8 +67,17 @@ describe('Form', () => {
expect(spies.stopPropagationCalled).to.be.true;
});

it('should abort when form is pristine', () => {
let cbCalled = false;
const { event } = generateFakeSubmissionEvent({ attrs: { pristine: true } });

onSubmit(event, initValues, () => cbCalled = true);

expect(cbCalled).to.be.false;
});

it('should abort when validation fails', () => {
const { event, spies } = generateFakeSubmissionEvent({ valid: false});
const { event, spies } = generateFakeSubmissionEvent({ valid: false });

onSubmit(event, initValues, noop);

Expand Down

0 comments on commit 5097a9a

Please sign in to comment.