Skip to content

Commit

Permalink
transformers docs
Browse files Browse the repository at this point in the history
  • Loading branch information
OxCom committed Sep 8, 2020
1 parent 9e4d787 commit 00d1e35
Showing 1 changed file with 61 additions and 6 deletions.
67 changes: 61 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,7 @@ npm i constraint-validator --save

## Basic usage
```javascript
import {
Form,
NotBlank,
Email,
Length
} from 'constraint-validator';
import { Form, NotBlank, Email, Length } from 'constraint-validator';

const form = new Form();

Expand Down Expand Up @@ -57,6 +52,66 @@ In case of form data is not valid the ```errors``` object contains properties (r
]
}
```
## Data transformers
Data transformers are used to translate the data for a field into a other format and back. The data transformers
act as middleware and will be executed in the same order as they were applied.

There are 2 types of data transformers:
- **transformer** - executes before validation process
- **reverseTransformers** - executes after validation process

#### Form data transformers
```javascript
import { Form, NotBlank, Email } from 'constraint-validator';

const form = new Form();

form
.add('email', [
new NotBlank(),
new Email(),
])
// next transformers will be applied to the form data
.addTransformer(data => {
data.email += '@example.com'

return data;
})
.addReverseTransformer(data => {
data.email = data.email.replace(/@example.com/, '@example.me');

return data;
});

form.validate({email: 'email'});

console.log(form.getData());
// Output:
// {"email": "[email protected]"}
```

#### Field data transformers
```javascript
import { Form, NotBlank, Email } from 'constraint-validator';

const form = new Form();

form
.add('email', [
new NotBlank(),
new Email(),
])
.get('email')
// next transformers will be applied to the 'email' field only
.addTransformer(value => value + '@example.com')
.addReverseTransformer(value => value.replace(/@example.com/, '@example.me'));

form.validate({email: 'email'});

console.log(form.getData());
// Output:
// {"email": "[email protected]"}
```


## Documentation
Expand Down

0 comments on commit 00d1e35

Please sign in to comment.