-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-mix-controlled-with-uncontrolled.ts
75 lines (73 loc) · 2.54 KB
/
no-mix-controlled-with-uncontrolled.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { TSESLint } from '@typescript-eslint/experimental-utils';
import { hasProp } from 'jsx-ast-utils';
import { capitalize } from '../utils/capitalize';
import { docsUrl } from '../utils/docsUrl';
import { getTagName } from '../utils/getTagName';
import { isCheckboxOrRadioInput } from '../utils/isCheckboxOrRadioInput';
import { isFormFieldTags } from '../utils/isFormFieldTags';
const rule: TSESLint.RuleModule<'no-mix-controlled-with-uncontrolled', []> = {
meta: {
docs: {
description:
'Forbid to specify both value/checked and defaultValue/defaultChecked props to form fields',
recommended: 'error',
url: docsUrl('no-mix-controlled-with-uncontrolled'),
},
messages: {
'no-mix-controlled-with-uncontrolled':
'{{capitalizeTagName}} elements must be either controlled or uncontrolled (specify either the {{valueName}} prop, or the {{defaultValueName}} prop, but not both). Decide between using a controlled or uncontrolled {{tagName}} element and remove one of these props.',
},
schema: [],
type: 'problem',
},
create: (context) => {
return {
JSXElement(node) {
const tagName = getTagName(node);
if (!isFormFieldTags(node)) {
return;
}
if (isCheckboxOrRadioInput(node)) {
const hasCheckedProp = hasProp(
node.openingElement.attributes,
'checked'
);
const hasDefaultCheckedProp = hasProp(
node.openingElement.attributes,
'defaultChecked'
);
if (hasCheckedProp && hasDefaultCheckedProp) {
context.report({
node,
messageId: 'no-mix-controlled-with-uncontrolled',
data: {
tagName,
capitalizeTagName: capitalize(tagName),
valueName: 'checked',
defaultValueName: 'defaultChecked',
},
});
}
}
const hasValueProp = hasProp(node.openingElement.attributes, 'value');
const hasDefaultValueProp = hasProp(
node.openingElement.attributes,
'defaultValue'
);
if (hasValueProp && hasDefaultValueProp) {
context.report({
node,
messageId: 'no-mix-controlled-with-uncontrolled',
data: {
tagName,
capitalizeTagName: capitalize(tagName),
valueName: 'value',
defaultValueName: 'defaultValue',
},
});
}
},
};
},
};
export default rule;