# API
- [Formsy](#formsy)
- [mapping](#mapping)
- [validationErrors](#validationErrors)
- [onSubmit()](#onSubmit)
- [onValid()](#onValid)
- [onInvalid()](#onInvalid)
- [onValidSubmit()](#onValidsubmit)
- [onInvalidSubmit()](#onInvalidsubmit)
- [onChange()](#onChange)
- [reset()](#reset)
- [getModel()](#getModel)
- [updateInputsWithError()](#updateInputsWithError)
- [preventExternalInvalidation](#preventExternalInvalidation)
- [withFormsy](#withFormsy)
- [name](#name)
- [innerRef](#innerRef)
- [value](#value)
- [validations](#validations)
- [validationError](#validationError)
- [validationErrors](#validationErrors)
- [required](#required)
- [getValue()](#getvalue)
- [setValue()](#setValue)
- [resetValue()](#resetValue)
- [getErrorMessage()](#getErrorMessage)
- [getErrorMessages()](#getErrorMessages)
- [isValid()](#isValid)
- [isValidValue()](#isValidValue)
- [isRequired()](#isRequired)
- [showRequired()](#showRequired)
- [showError()](#showError)
- [isPristine()](#isPristine)
- [isFormDisabled()](#isFormDisabled)
- [isFormSubmitted()](#isFormSubmitted)
- [formNoValidate](#formNoValidate)
- [propTypes](#propTypes)
- [addValidationRule](#addValidationRule)
- [Validators](#validators)
### Formsy
`import Formsy from 'react-formsy';`
#### mapping
```jsx
class MyForm extends React.Component {
mapInputs(inputs) {
return {
'field1': inputs.foo,
'field2': inputs.bar
};
}
submit(model) {
model; // {field1: '', field2: ''}
}
render() {
return (
);
}
}
```
Use mapping to change the data structure of your input elements. This structure is passed to the submit hooks.
#### validationErrors
You can manually pass down errors to your form. In combination with `onChange` you are able to validate using an external validator.
```jsx
class Form extends React.Component {
state = { validationErrors: {} };
validateForm = (values) => {
if (!values.foo) {
this.setState({
validationErrors: {
foo: 'Has no value'
}
});
} else {
this.setState({
validationErrors: {}
});
}
}
render() {
return (
);
}
}
```
#### onSubmit(data, resetForm, invalidateForm)
```jsx
```
Takes a function to run when the submit button has been clicked.
The first argument is the data of the form. The second argument will reset the form. The third argument will invalidate the form by taking an object that maps to inputs. This is useful for server side validation. E.g. `{email: "This email is taken"}`. Resetting or invalidating the form will cause **setState** to run on the form element component.
#### onValid()
```jsx
```
Whenever the form becomes valid the "onValid" handler is called. Use it to change state of buttons or whatever your heart desires.
#### onInvalid()
```jsx
```
Whenever the form becomes invalid the "onInvalid" handler is called. Use it to for example revert "onValid" state.
#### onValidSubmit(model, resetForm, invalidateForm)
```jsx
```
Triggers when form is submitted with a valid state. The arguments are the same as on `onSubmit`.
#### onInvalidSubmit(model, resetForm, invalidateForm)
```jsx
```
Triggers when form is submitted with an invalid state. The arguments are the same as on `onSubmit`.
#### onChange(currentValues, isChanged)
```jsx
```
"onChange" triggers when setValue is called on your form elements. It is also triggered when dynamic form elements have been added to the form. The "currentValues" is an object where the key is the name of the input and the value is the current value. The second argument states if the forms initial values actually has changed.
#### reset(values)
```jsx
class MyForm extends React.Component {
resetForm = () => {
this.refs.form.reset();
}
render() {
return (
...
);
}
}
```
Manually reset the form to its pristine state. You can also pass an object that inserts new values into the inputs. Keys are name of input and value is of course the value.
#### getModel()
```jsx
class MyForm extends React.Component {
getMyData = () => {
alert(this.refs.form.getModel());
}
render() {
return (
...
);
}
}
```
Manually get values from all registered components. Keys are name of input and value is of course the value.
#### updateInputsWithError(errors)
```jsx
class MyForm extends React.Component {
someFunction = () => {
this.refs.form.updateInputsWithError({
email: 'This email is taken',
'field[10]': 'Some error!'
});
}
render() {
return (
...
);
}
}
```
Manually invalidate the form by taking an object that maps to inputs. This is useful for server side validation. You can also use a third parameter to the [`onSubmit`](#onSubmit), [`onValidSubmit`](#onValid) or [`onInvalidSubmit`](#onInvalid).
#### preventExternalInvalidation
```jsx
class MyForm extends React.Component {
onSubmit(model, reset, invalidate) {
invalidate({
foo: 'Got some error'
});
}
render() {
return (
...
);
}
}
```
With the `preventExternalInvalidation` the input will not be invalidated though it has an error.
### `withFormsy`
All Formsy input components must be wrapped in the `withFormsy` higher-order component, which provides the following properties and methods through `props`.
```jsx
import { withFormsy } from 'formsy-react';
class MyInput extends React.Component {
render() {
return (
this.props.setValue(e.target.value)}/>
);
}
}
export default withFormsy(MyInput);
```
#### name
```jsx
```
The name is required to register the form input component in the form. You can also use dot notation. This will result in the "form model" being a nested object. `{email: 'value', address: {street: 'value'}}`.
#### innerRef
Use an `innerRef` prop to get a reference to your DOM node.
```jsx
class MyForm extends React.Component {
componentDidMount() {
this.searchInput.focus()
}
render() {
return (
{ this.searchInput = c; }} />
);
}
}
```
#### value
```jsx
```
You should always use the [**getValue()**](#getvalue) method inside your formsy form element. To pass an initial value, use the value attribute. This value will become the "pristine" value and any reset of the form will bring back this value.
#### validations
```jsx
```
A comma separated list with validation rules. Take a look at [**Validators**](#validators) to see default rules. Use ":" to separate argument passed to the validator. The argument will go through a **JSON.parse** converting them into correct JavaScript types. Meaning:
```jsx
```
Works just fine.
#### validationError
```jsx
```
The message that will show when the form input component is invalid. It will be used as a default error.
#### validationErrors
```jsx
```
The message that will show when the form input component is invalid. You can combine this with `validationError`. Keys not found in `validationErrors` defaults to the general error message.
#### required
```jsx
```
A property that tells the form that the form input component value is required. By default it uses `isDefaultRequiredValue`, but you can define your own definition of what defined a required state.
```jsx
```
Would be typical for a checkbox type of form element that must be checked, e.g. agreeing to Terms of Service.
#### getValue()
```jsx
class MyInput extends React.Component {
render() {
return (
);
}
}
```
Gets the current value of the form input component.
#### setValue(value\[, validate = true])
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
return (
);
}
}
```
Sets the value of your form input component. Notice that it does not have to be a text input. Anything can set a value on the component. Think calendars, checkboxes, autocomplete stuff etc. Running this method will trigger a **setState()** on the component and do a render.
You can also set the value without forcing an immediate validation by passing a second parameter of `false`. This is useful in cases where you want to only validate on blur / change / etc.
#### resetValue()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
return (
);
}
}
```
Resets to empty value. This will run a **setState()** on the component and do a render.
#### getErrorMessage()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
return (
{this.props.getErrorMessage()}
);
}
}
```
Will return the validation message set if the form input component is invalid. If form input component is valid it returns **null**.
#### getErrorMessages()
Will return the validation messages set if the form input component is invalid. If form input component is valid it returns empty array.
#### isValid()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
var face = this.props.isValid() ? ':-)' : ':-(';
return (
{face}{this.props.getErrorMessage()}
);
}
}
```
Returns the valid state of the form input component.
#### isValidValue()
You can pre-verify a value against the passed validators to the form element.
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
if (this.isValidValue(event.target.value)) {
this.props.setValue(event.target.value);
}
}
render() {
return ;
}
});
class MyForm extends React.Component {
render() {
return (
);
}
}
```
#### isRequired()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
return (
);
}
}
```
Returns true if the required property has been passed.
#### showRequired()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
var className = this.props.showRequired() ? 'required' : '';
return (
{this.props.getErrorMessage()}
);
}
}
```
Lets you check if the form input component should indicate if it is a required field. This happens when the form input component value is empty and the required prop has been passed.
#### showError()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
var className = this.props.showRequired() ? 'required' : this.props.showError() ? 'error' : '';
return (
{this.props.getErrorMessage()}
);
}
}
```
Lets you check if the form input component should indicate if there is an error. This happens if there is a form input component value and it is invalid or if a server error is received.
#### isPristine()
```jsx
class MyInput extends React.Component {
changeValue = (event) => {
this.props.setValue(event.currentTarget.value);
}
render() {
return (
{this.props.isPristine() ? 'You have not touched this yet' : ''}
);
}
}
```
By default all Formsy input elements are pristine, which means they are not "touched". As soon as the [**setValue**](#setValue) method is run it will no longer be pristine.
**note!** When the form is reset (using `reset(...)`) the inputs are reset to their pristine state.
#### isFormDisabled()
```jsx
class MyInput extends React.Component {
render() {
return (
);
}
}
React.render();
```
You can now disable the form itself with a prop and use **isFormDisabled()** inside form elements to verify this prop.
#### isFormSubmitted()
```jsx
class MyInput extends React.Component {
render() {
var error = this.props.isFormSubmitted() ? this.props.getErrorMessage() : null;
return (
{error}
);
}
}
```
You can check if the form has been submitted.
#### formNoValidate
To avoid native validation behavior on inputs, use the React `formNoValidate` property.
```jsx
class MyInput extends React.Component {
render() {
return (
);
}
}
```
### `propTypes`
If you are using React's PropType type checking, you can spread Formsy’s propTypes into your local propTypes to avoid having to repeatedly add `withFormsy`’s methods to your components.
```jsx
import PropTypes from 'prop-types';
import { propTypes } from 'formsy-react';
class MyInput extends React.Component {
static propTypes = {
firstProp: PropTypes.string,
secondProp: PropTypes.object,
...propTypes
}
}
MyInput.propTypes = {
firstProp: PropTypes.string,
secondProp: PropTypes.object,
...propTypes,
};
```
### `addValidationRule(name, ruleFunc)`
`import { addValidationRule } from 'formsy-react';`
An example:
```jsx
addValidationRule('isFruit', function (values, value) {
return ['apple', 'orange', 'pear'].indexOf(value) >= 0;
});
```
```jsx
```
Another example:
```jsx
addValidationRule('isIn', function (values, value, array) {
return array.indexOf(value) >= 0;
});
```
```jsx
```
Cross input validation:
```jsx
addValidationRule('isMoreThan', function (values, value, otherField) {
// The this context points to an object containing the values
// {childAge: "", parentAge: "5"}
// otherField argument is from the validations rule ("childAge")
return Number(value) > Number(values[otherField]);
});
```
```jsx
```
## Validators
**matchRegexp**
```jsx
```
Returns true if the value is thruthful
_For more complicated regular expressions (emoji, international characters) you can use [xregexp](https://github.com/slevithan/xregexp). See [this comment](https://github.com/christianalfoni/formsy-react/issues/407#issuecomment-266306783) for an example._
**isEmail**
```jsx
```
Return true if it is an email
**isUrl**
```jsx
```
Return true if it is an url
**isExisty**
```jsx
```
Returns true if the value is not undefined or null
**isUndefined**
```jsx
```
Returns true if the value is the undefined
**isEmptyString**
```jsx
```
Returns true if the value is an empty string
**isTrue**
```jsx
```
Returns true if the value is the boolean true
**isFalse**
```jsx
```
Returns true if the value is the boolean false
**isAlpha**
```jsx
```
Returns true if string is only letters
**isNumeric**
```jsx
```
Returns true if string only contains numbers. Examples: 42; -3.14
**isAlphanumeric**
```jsx
```
Returns true if string only contains letters or numbers
**isInt**
```jsx
```
Returns true if string represents integer value. Examples: 42; -12; 0
**isFloat**
```jsx
```
Returns true if string represents float value. Examples: 42; -3.14; 1e3
**isWords**
```jsx
```
Returns true if string is only letters, including spaces and tabs
**isSpecialWords**
```jsx
```
Returns true if string is only letters, including special letters (a-z,ú,ø,æ,å)
**equals:value**
```jsx
```
Return true if the value from input component matches value passed (==).
**equalsField:fieldName**
```jsx
```
Return true if the value from input component matches value passed (==).
**isLength:length**
```jsx
```
Returns true if the value length is the equal.
**minLength:length**
```jsx
```
Return true if the value is more or equal to argument.
**Also returns true for an empty value.** If you want to get false, then you should use [`required`](#required) additionally.
**maxLength:length**
```jsx
```
Return true if the value is less or equal to argument