Skip to content
This repository has been archived by the owner on Jul 5, 2019. It is now read-only.

Add type support to form validation #13

Merged
merged 4 commits into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/neoform-validation/src/fieldValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ const fieldValidation = (Target) => {
}
}

validate() {
validate(event) {
if (this.props.validator) {
this.context.neoform.validate(this.props.name);
const type = event ? event.type : 'unknown';

this.context.neoform.validate(this.props.name, type);
}
}

Expand Down
6 changes: 3 additions & 3 deletions packages/neoform-validation/src/formValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ const formValidation = (Target) => {
return this.state.fields[name] || {};
}

validateField(name) {
validateField(name, type) {
const validator = this.validators[name];
const value = this.context.neoform.getValue(name);

validator(value)
validator(value, type)
.then((message) => {
this.setState((prevState) => ({
fields: {
Expand Down Expand Up @@ -90,7 +90,7 @@ const formValidation = (Target) => {
const validator = this.validators[name];
const value = this.context.neoform.getValue(name);

return validator(value)
return validator(value, 'submit')
.then((message) => {
fields[name] = {
status: true,
Expand Down
7 changes: 6 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ Where:
"Validator" is just a Promise. Rejected one is for `validationStatus: false` prop and resolved is for `validationStatus: true`. An optional argument passed to a rejected or fulfilled Promise becomes `validationMessage` prop.

```js
export const requiredValidator = (value) => {
export const requiredValidator = (value, type) => {
if (value === '') {
return Promise.reject('💩');
}
Expand All @@ -317,6 +317,11 @@ export const requiredValidator = (value) => {
};
```

Where:

* `value` – field value for validation
* `type` – event type. Can be `submit`, `change`, `blur` or anything you will provide to field `validate` method

It's up to you how to manage multiple validators — with a simple `Promise.all()` or some complex asynchronous sequences — as long as validator returns a single Promise.

To use a validator you should just pass it in a `validator` prop to an individual field:
Expand Down