Skip to content

Commit 3f19afc

Browse files
authored
fix(validation): wrong condition for required field (#99)
1 parent ea96f7c commit 3f19afc

File tree

2 files changed

+69
-4
lines changed

2 files changed

+69
-4
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { isStepInError } from '../error.util.ts';
2+
3+
describe('isStepInError', () => {
4+
let schema;
5+
let errors;
6+
let fieldsToCheckByStep;
7+
let dirtyFields;
8+
let defaultValues;
9+
10+
beforeEach(() => {
11+
schema = {
12+
fields: {
13+
myField: {
14+
id: 'myField',
15+
type: 'text',
16+
validation: {
17+
required: {
18+
value: false,
19+
key: 'required',
20+
message: 'please fill this field',
21+
},
22+
},
23+
},
24+
},
25+
stepsById: ['step1'],
26+
steps: {
27+
step1: {
28+
id: 'step1',
29+
fieldsById: ['myField'],
30+
submit: { label: 'submit' },
31+
},
32+
},
33+
};
34+
errors = {};
35+
fieldsToCheckByStep = ['myField'];
36+
dirtyFields = {};
37+
defaultValues = {};
38+
});
39+
40+
it('should return false if the field is empty and not required', () => {
41+
const isInError = isStepInError({
42+
schema,
43+
errors,
44+
fieldsToCheckByStep,
45+
dirtyFields,
46+
defaultValues,
47+
});
48+
49+
expect(isInError).toBe(false);
50+
});
51+
52+
it('should return true if the field is empty and required', () => {
53+
schema.fields.myField.validation.required.value = true;
54+
55+
const isInError = isStepInError({
56+
schema,
57+
errors,
58+
fieldsToCheckByStep,
59+
dirtyFields,
60+
defaultValues,
61+
});
62+
63+
expect(isInError).toBe(true);
64+
});
65+
});

libs/form-builder/src/lib/utils/error.util.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,13 @@ export const getFieldsToCheckByStep = ({
1717
return fieldsToCheck;
1818
};
1919

20-
export const isFieldInError = ({ fieldToCheck, errors }: { fieldToCheck: string; errors: FieldErrors }) =>
20+
const isFieldInError = ({ fieldToCheck, errors }: { fieldToCheck: string; errors: FieldErrors }) =>
2121
!!(errors && errors[fieldToCheck]);
2222

23-
export const isFieldRequired = ({ schema, fieldToCheck }: { schema: FormSchema; fieldToCheck: string }) =>
24-
schema?.fields?.[fieldToCheck]?.validation?.[DEFAULT_RULES_NAMES.required];
23+
const isFieldRequired = ({ schema, fieldToCheck }: { schema: FormSchema; fieldToCheck: string }): boolean =>
24+
!!schema?.fields?.[fieldToCheck]?.validation?.[DEFAULT_RULES_NAMES.required]?.value;
2525

26-
export const isFieldNotDirtyAndEmpty = ({
26+
const isFieldNotDirtyAndEmpty = ({
2727
fieldToCheck,
2828
dirtyFields,
2929
defaultValues,

0 commit comments

Comments
 (0)