Skip to content

Commit f74ccf0

Browse files
committed
add ability to pass failureCallback to ifValid helper method
- adjust `ifValid` helper method to be able to accept `failureCallback` as second argument which is executed if form has validation errors - update README
1 parent e7940c2 commit f74ccf0

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,9 @@ for the Form to be able to use validations.
124124
additional iteration that passes `null` and length of items to `iteratee`
125125
- `getValidationErrors()` - returns validation errors.
126126
- `performValidation()` - runs validation routines and sets errors.
127-
- `ifValid(callback)` - runs validation routines, sets errors, and executes
128-
`callback` if there were no errors.
127+
- `ifValid(successCallback, failureCallback)` - runs validation routines, sets errors,
128+
and executes `successCallback` if there were no errors. Otherwise, executes
129+
`failureCallback`, if is was passed, **or** `props.onValidationFailed`
129130
- `getErrors()` - returns an errors object.
130131
- `getError(name)` - returns an error for an input with a given `name`.
131132
- `setErrors(errors)` - sets `errors` (object) as form's errors.

src/Form.jsx

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,19 +144,20 @@ export default class Form extends (PureComponent || Component) {
144144
return typeof validationz === 'function' ? validationz.call(this) : validationz;
145145
}
146146

147-
ifValid(callback) {
147+
ifValid(successCallback, failureCallback) {
148148
const { onValidationFailed } = this.props;
149149
const errors = this.getValidationErrors();
150+
failureCallback = failureCallback || onValidationFailed;
150151

151152
this.setErrors(errors, function() {
152153
const valid = Object.getOwnPropertyNames(errors).length === 0;
153154

154-
if (valid && callback) {
155-
callback();
155+
if (valid && successCallback) {
156+
successCallback();
156157
}
157158

158-
if (!valid && onValidationFailed) {
159-
onValidationFailed(errors, this);
159+
if (!valid && failureCallback) {
160+
failureCallback(errors, this);
160161
}
161162
});
162163

test/Form.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,14 @@ describe('<Form />', function() {
571571
this.test.wrapper.instance().ifValid(spy);
572572
expect(spy).toNotHaveBeenCalled();
573573
});
574+
575+
it('triggers failure callback if it was passed', function() {
576+
const successSpy = createSpy();
577+
const failureSpy = createSpy();
578+
this.test.wrapper.instance().ifValid(successSpy, failureSpy);
579+
expect(successSpy).toNotHaveBeenCalled();
580+
expect(failureSpy).toHaveBeenCalled();
581+
});
574582
});
575583
});
576584

0 commit comments

Comments
 (0)