You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
**React Constraint Validation** provides a HOC and some standard validators. The HOC can be used to enhance form components of your preferred form framework e.g. Formik.
25
25
26
-
Limitation: Actually it currently only supports Formik ;) Support for other form frameworks like Redux-Form is planned with one of the next releases.
26
+
Limitation: Actually it currently only supports Formik ;) Support for other form frameworks like React Final Form is planned with one of the next releases.
27
27
28
28
### Getting started
29
29
30
30
Add react-constraint-validation:
31
31
32
-
$ npm install react-constraint-validation --save
32
+
npm i react-constraint-validation # or yarn add react-constraint-validation
33
33
34
34
Enhance a Formik field component with validation (should be done once per application):
35
35
36
-
const NumberField = withValidator({required, min, max },{number})(Field);
A complete example can be found in [examples/formik](https://github.com/pstrh/react-constraint-validation/blob/master/examples/formik/src/components/FieldLevelValidation.tsx).
45
49
46
-
### WIP
50
+
### Validators
51
+
52
+
**React Constraint Validation** provides the following validations out-of-the-box:
53
+
*`required` checks that the given value is not null, undefined or an empty string
54
+
*`min` checks that the given number value is equal or greater than the given lower bound
55
+
*`max` checks that the given value is smaller than or equal to the given upper bound
56
+
*`minLength` checks that the length of the given string value is equal or greater than the given length
57
+
*`maxLength` checks that the length of the given string value is smaller or equal to the given length
58
+
*`pattern` checks if the given value matches a RegEx pattern
59
+
*`number` checks if the given value is a number
60
+
*`email` checks if the given value is a valid email (via a RegEx pattern)
61
+
62
+
### The withValidator HOC (experimental)
63
+
64
+
Fields wrapped with the withValidator HOC can be configured with two kinds of validators:
65
+
- (optional) validators that can be activated via field props
66
+
- default validators that should be always executed as they are inherent to the specific field type
NumberField has the optional validations `required`, `min` and `max`. These validations can (but don't have to) be set via field props.
77
+
Whereas the `number` validation is defined as default validation and is always applied.
78
+
Textfield on the other hand doesn't enforce a default validation. Here only the optional validations `required`,
79
+
`minLength` and `maxLength` are configured on the field.
80
+
81
+
### Default error messages
82
+
83
+
The following object defines the default error messages:
84
+
85
+
```
86
+
const defaultMessages: Messages = {
87
+
"required": "{name} is required",
88
+
"min": "{name} must be greater than {minValue}",
89
+
"max": "{name} must be less than {maxValue}",
90
+
"minLength": "{name} must have at least {minLength} characters",
91
+
"maxLength": "{name} must have less than {maxLength} characters",
92
+
"pattern": "{name} does not match the pattern {pattern}",
93
+
"number": "{name} must be a number",
94
+
"email": "{name} is not a valid email"
95
+
};
96
+
```
97
+
98
+
The placeholders `{name}`, `{minValue}`, `{maxValue}` and so on are replaced if the actual error message is created. `name` is the name of the form field. The other placeholders like `{minValue}` provide access to the respective validation constraints.
99
+
100
+
### Custom error messages
101
+
102
+
If you want to override the default error messages, just initialize the Validator with a custom error message object as shown in the following example:
103
+
104
+
```
105
+
import * as Validator from "react-constraint-validation";
106
+
107
+
const customErrorMessages = {
108
+
"required": "This field is required", // override without placeholder
109
+
"number": "Enter only numbers in {name}"
110
+
};
111
+
112
+
Validator.init(customErrorMessages);
113
+
```
114
+
115
+
In the `init` method the custom error messages are merged with the default messages. As you can see in the `required` example, it's not necessary to use the placeholders of the default error
116
+
messages. Usage of the placeholders in the custom error messages is optional.
117
+
118
+
If you want to create custom error messages for a specific field, you can just add an additional attribute following
119
+
the pattern `required.<name>` (where name is the name attribute of the field).
120
+
121
+
```
122
+
import * as Validator from "react-constraint-validation";
123
+
124
+
const customErrorMessages = {
125
+
"required": "This field is required", // Error message for all other fields
126
+
"required.firstName": "First name is required", // Error message for field 'firstName'
127
+
"required.lastName": "Last name is required", // Error message for field 'lastName'
128
+
"number": "Enter only numbers in {name}"
129
+
};
130
+
131
+
Validator.init(customErrorMessages);
132
+
```
133
+
134
+
E.g. for the required validation on the field 'firstName' react-constraint-validation will first check if the attribute
135
+
`required.firstname` is contained in the errorMessage object. If `required.firstname` is not present it will
136
+
retreive the error message configured via the `required` attribute.
137
+
138
+
### Localisation
139
+
140
+
Localisation of the error messages can be done in the same way as you customize the default error messages. Just initialize the Validator with an object of localized error messages as shown below:
141
+
142
+
```
143
+
import * as Validator from "react-constraint-validation";
144
+
145
+
// should be content of your localisation file
146
+
const germanMessages: Messages = {
147
+
"required": "Bitte fülllen Sie dieses Feld",
148
+
"min": "Der Wert des Feldes muss größer als {minValue} sein",
149
+
"max": "Der Wert des Feldes darf nicht größer sein als {maxValue}",
150
+
"minLength": "Bitte geben Sie mindestens {minLength} Zeichen ein",
151
+
"maxLength": "Bitte geben Sie nicht mehr als {maxLength} Zeichen ein",
152
+
"pattern": "Die Eingabe hat ein ungültiges Format",
153
+
"number": "Hier sind nur Zahlen erlaubt",
154
+
"email": "Die Email-Adresse ist nicht korrekt"
155
+
};
156
+
157
+
// to be called if user locale changes
158
+
Validator.init(germanMessages);
159
+
```
160
+
161
+
### Create custom validators
162
+
163
+
If needed, you can create additional custom validators and configured them on your field via the withValidator HOC.
164
+
165
+
The following example illustrates how to create a custom validator. As a sample use case we create an "UpperCaseValidator".
166
+
167
+
```
168
+
import { init, required, resolveErrorMessage, withValidator } from "react-constraint-validation";
The type `ValidationFunctionWithParam` can be used if the validator takes an argument like `minLenght={5}`.
199
+
200
+
### Field-Level vs. Form-Level validation
201
+
202
+
**React Constraint Validation** is designed to provide standard fields with build-in validation support (EmailField, NumberField and so on).
203
+
204
+
Therefore it might be useful if you need to build an application with many form fields or if you provide a component library for a number of different applications. If you only need to implement one or two small forms in your application using react-constraint-validation might be less useful.
205
+
206
+
Furthermore as this small library is designed to provide standard fields it is solely focused on field-level validation. Cross field or multi field validations is an aspect that depends on the individual form rather than on the single field. It's therefore better done on the form level
207
+
(unfortunetly there is currently an issue with Formik as it execute form level validation before the field level validation).
208
+
209
+
### About
210
+
211
+
This project is experimental and still work in progress. Feel free to try. Feedback, suggestions and any kind of contribution is welcome.
47
212
48
-
This is a new project. The basic functionality is there and can be used.
213
+
### License
49
214
50
-
Any feedback, suggestions and contributions are welcome.
0 commit comments