Compare commits

..

1 Commits

Author SHA1 Message Date
Semigradsky 231ac4c7de Added possibility to passing validation parameters to validation errors messages. 2015-12-18 18:14:01 +03:00
28 changed files with 268 additions and 235 deletions

View File

@ -1,7 +0,0 @@
{
"presets": [
"react",
"es2015",
"stage-2"
]
}

2
.gitignore vendored
View File

@ -1,2 +1,4 @@
.DS_Store
build
node_modules node_modules
lib lib

View File

@ -1,8 +1,3 @@
.babelrc build/
.editorconfig bower.json
.travis.yml Gulpfile.js
testrunner.js
webpack.production.config.js
examples/
release/
tests/

70
API.md
View File

@ -1,5 +1,6 @@
# API # API
- [Formsy.defaults - DEPRECATED](#formsydefaults)
- [Formsy.Form](#formsyform) - [Formsy.Form](#formsyform)
- [className](#classname) - [className](#classname)
- [mapping](#mapping) - [mapping](#mapping)
@ -12,20 +13,20 @@
- [onChange()](#onchange) - [onChange()](#onchange)
- [reset()](#resetform) - [reset()](#resetform)
- [getModel()](#getmodel) - [getModel()](#getmodel)
- [updateInputsWithError()](#updateinputswitherrorerrors) - [updateInputsWithError()](#updateinputswitherror)
- [preventExternalInvalidation](#preventexternalinvalidation) - [preventExternalInvalidation](#preventexternalinvalidation)
- [Formsy.Mixin](#formsymixin) - [Formsy.Mixin](#formsymixin)
- [name](#name) - [name](#name)
- [value](#value) - [value](#value)
- [validations](#validations) - [validations](#validations)
- [validationError](#validationerror) - [validationError](#validationerror)
- [validationErrors](#validationerrors-1) - [validationErrors](#validationerrors)
- [required](#required) - [required](#required)
- [getValue()](#getvalue) - [getValue()](#getvalue)
- [setValue()](#setvalue) - [setValue()](#setvalue)
- [hasValue() - DEPRECATED](#hasvalue)
- [resetValue()](#resetvalue) - [resetValue()](#resetvalue)
- [getErrorMessage()](#geterrormessage) - [getErrorMessage()](#geterrormessage)
- [getErrorMessages()](#geterrormessages)
- [isValid()](#isvalid) - [isValid()](#isvalid)
- [isValidValue()](#isvalidvalue) - [isValidValue()](#isvalidvalue)
- [isRequired()](#isrequired) - [isRequired()](#isrequired)
@ -37,11 +38,12 @@
- [validate](#validate) - [validate](#validate)
- [formNoValidate](#formnovalidate) - [formNoValidate](#formnovalidate)
- [Formsy.HOC](#formsyhoc) - [Formsy.HOC](#formsyhoc)
- [innerRef](#innerRef)
- [Formsy.Decorator](#formsydecorator) - [Formsy.Decorator](#formsydecorator)
- [Formsy.addValidationRule](#formsyaddvalidationrule) - [Formsy.addValidationRule](#formsyaddvalidationrule)
- [Validators](#validators) - [Validators](#validators)
### <a name="formsydefaults">Formsy.defaults(options) - DEPRECATED</a>
### <a name="formsyform">Formsy.Form</a> ### <a name="formsyform">Formsy.Form</a>
#### <a name="classname">className</a> #### <a name="classname">className</a>
@ -249,7 +251,7 @@ You should always use the [**getValue()**](#getvalue) method inside your formsy
} }
}}/> }}/>
``` ```
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: An 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 ```jsx
<MyInputComponent name="fruit" validations="isIn:['apple', 'orange']"/> <MyInputComponent name="fruit" validations="isIn:['apple', 'orange']"/>
@ -269,11 +271,13 @@ The message that will show when the form input component is invalid. It will be
name="email" name="email"
validations={{ validations={{
isEmail: true, isEmail: true,
maxLength: 50 maxLength: 50,
someCustomValidation: [1, 2, 3]
}} }}
validationErrors={{ validationErrors={{
isEmail: 'You have to type valid email', isEmail: 'You have to type valid email',
maxLength: 'You can not type in more than 50 characters' maxLength: 'You can not type in more than {0} characters',
someCustomValidation: '{0} + {1} = {2}'
}} }}
/> />
``` ```
@ -320,6 +324,25 @@ var MyInput = React.createClass({
``` ```
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. 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.
#### <a name="hasvalue">hasValue() - DEPRECATED</a>
```jsx
var MyInput = React.createClass({
mixins: [Formsy.Mixin],
changeValue: function (event) {
this.setValue(event.currentTarget.value);
},
render: function () {
return (
<div>
<input type="text" onChange={this.changeValue} value={this.getValue()}/>
{this.hasValue() ? 'There is a value here' : 'No value entered yet'}
</div>
);
}
});
```
The hasValue() method helps you identify if there actually is a value or not. The only invalid value in Formsy is an empty string, "". All other values are valid as they could be something you want to send to the server. F.ex. the number zero (0), or false.
#### <a name="resetvalue">resetValue()</a> #### <a name="resetvalue">resetValue()</a>
```jsx ```jsx
var MyInput = React.createClass({ var MyInput = React.createClass({
@ -358,9 +381,6 @@ var MyInput = React.createClass({
``` ```
Will return the validation message set if the form input component is invalid. If form input component is valid it returns **null**. Will return the validation message set if the form input component is invalid. If form input component is valid it returns **null**.
#### <a name="geterrormessages">getErrorMessages()</a>
Will return the validation messages set if the form input component is invalid. If form input component is valid it returns empty array.
#### <a name="isvalid">isValid()</a> #### <a name="isvalid">isValid()</a>
```jsx ```jsx
var MyInput = React.createClass({ var MyInput = React.createClass({
@ -567,7 +587,7 @@ The same methods as the mixin are exposed to the HOC version of the element comp
```jsx ```jsx
import {HOC} from 'formsy-react'; import {HOC} from 'formsy-react';
class MyInputHoc extends React.Component { class MyInput extends React.Component {
render() { render() {
return ( return (
<div> <div>
@ -576,26 +596,7 @@ class MyInputHoc extends React.Component {
); );
} }
}; };
export default HOC(MyInputHoc); export default HOC(MyInput);
```
#### <a name="innerRef">innerRef</a>
Use an `innerRef` prop to get a reference to your DOM node.
```jsx
var MyForm = React.createClass({
componentDidMount() {
this.searchInput.focus()
},
render: function () {
return (
<Formsy.Form>
<MyInputHoc name="search" innerRef={(c) => { this.searchInput = c; }} />
</Formsy.Form>
);
}
})
``` ```
### <a name="formsydecorator">Formsy.Decorator</a> ### <a name="formsydecorator">Formsy.Decorator</a>
@ -624,7 +625,7 @@ Formsy.addValidationRule('isFruit', function (values, value) {
}); });
``` ```
```jsx ```jsx
<MyInputComponent name="fruit" validations="isFruit"/> <MyInputComponent name="fruit" validations="'isFruit"/>
``` ```
Another example: Another example:
```jsx ```jsx
@ -657,8 +658,6 @@ Formsy.addValidationRule('isMoreThan', function (values, value, otherField) {
``` ```
Returns true if the value is thruthful 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** **isEmail**
```jsx ```jsx
<MyInputComponent name="foo" validations="isEmail"/> <MyInputComponent name="foo" validations="isEmail"/>
@ -766,8 +765,7 @@ Returns true if the value length is the equal.
```jsx ```jsx
<MyInputComponent name="number" validations="minLength:1"/> <MyInputComponent name="number" validations="minLength:1"/>
``` ```
Return true if the value is more or equal to argument. 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** **maxLength:length**
```jsx ```jsx

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2014-2016 PatientSky A/S Copyright (c) 2014 Gloppens EDB Lag
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -6,6 +6,8 @@ A form input builder and validator for React JS
| [How to use](#how-to-use) | [API](/API.md) | [Examples](/examples) | | [How to use](#how-to-use) | [API](/API.md) | [Examples](/examples) |
|---|---|---| |---|---|---|
### From version 0.12.0 Formsy only supports React 0.13.1 and up
## <a name="background">Background</a> ## <a name="background">Background</a>
I wrote an article on forms and validation with React JS, [Nailing that validation with React JS](http://christianalfoni.github.io/javascript/2014/10/22/nailing-that-validation-with-reactjs.html), the result of that was this extension. I wrote an article on forms and validation with React JS, [Nailing that validation with React JS](http://christianalfoni.github.io/javascript/2014/10/22/nailing-that-validation-with-reactjs.html), the result of that was this extension.
@ -46,29 +48,29 @@ Complete API reference is available [here](/API.md).
#### Formsy gives you a form straight out of the box #### Formsy gives you a form straight out of the box
```jsx ```javascript
import Formsy from 'formsy-react'; /** @jsx React.DOM */
var Formsy = require('formsy-react');
const MyAppForm = React.createClass({ var MyAppForm = React.createClass({
getInitialState() { getInitialState: function () {
return { return {
canSubmit: false canSubmit: false
} }
}, },
enableButton() { enableButton: function () {
this.setState({ this.setState({
canSubmit: true canSubmit: true
}); });
}, },
disableButton() { disableButton: function () {
this.setState({ this.setState({
canSubmit: false canSubmit: false
}); });
}, },
submit(model) { submit: function (model) {
someDep.saveEmail(model.email); someDep.saveEmail(model.email);
}, },
render() { render: function () {
return ( return (
<Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}> <Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}>
<MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/> <MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/>
@ -82,31 +84,31 @@ Complete API reference is available [here](/API.md).
This code results in a form with a submit button that will run the `submit` method when the submit button is clicked with a valid email. The submit button is disabled as long as the input is empty ([required](/API.md#required)) or the value is not an email ([isEmail](/API.md#validators)). On validation error it will show the message: "This is not a valid email". This code results in a form with a submit button that will run the `submit` method when the submit button is clicked with a valid email. The submit button is disabled as long as the input is empty ([required](/API.md#required)) or the value is not an email ([isEmail](/API.md#validators)). On validation error it will show the message: "This is not a valid email".
#### Building a form element (required) #### Building a form element (required)
```jsx ```javascript
import Formsy from 'formsy-react'; /** @jsx React.DOM */
var Formsy = require('formsy-react');
const MyOwnInput = React.createClass({ var MyOwnInput = React.createClass({
// Add the Formsy Mixin // Add the Formsy Mixin
mixins: [Formsy.Mixin], mixins: [Formsy.Mixin],
// setValue() will set the value of the component, which in // setValue() will set the value of the component, which in
// turn will validate it and the rest of the form // turn will validate it and the rest of the form
changeValue(event) { changeValue: function (event) {
this.setValue(event.currentTarget.value); this.setValue(event.currentTarget.value);
}, },
render: function () {
render() {
// Set a specific className based on the validation // Set a specific className based on the validation
// state of this component. showRequired() is true // state of this component. showRequired() is true
// when the value is empty and the required prop is // when the value is empty and the required prop is
// passed to the input. showError() is true when the // passed to the input. showError() is true when the
// value typed is invalid // value typed is invalid
const className = this.showRequired() ? 'required' : this.showError() ? 'error' : null; var className = this.showRequired() ? 'required' : this.showError() ? 'error' : null;
// An error message is returned ONLY if the component is invalid // An error message is returned ONLY if the component is invalid
// or the server has returned an error message // or the server has returned an error message
const errorMessage = this.getErrorMessage(); var errorMessage = this.getErrorMessage();
return ( return (
<div className={className}> <div className={className}>
@ -128,11 +130,32 @@ The form element component is what gives the form validation functionality to wh
## Contribute ## Contribute
- Fork repo - Fork repo
- `npm install` - `npm install`
- `npm run examples` runs the development server on `localhost:8080` - `npm start` runs the development server on `localhost:8080`
- `npm test` runs the tests - `npm test` runs the tests
## License License
-------
[The MIT License (MIT)](/LICENSE) formsy-react is licensed under the [MIT license](LICENSE).
Copyright (c) 2014-2016 PatientSky A/S > The MIT License (MIT)
>
> Copyright (c) 2015 Gloppens EDB Lag
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.

View File

@ -1,6 +1,6 @@
{ {
"name": "formsy-react", "name": "formsy-react",
"version": "0.18.0", "version": "0.16.0",
"description": "A form input builder and validator for React JS", "description": "A form input builder and validator for React JS",
"repository": { "repository": {
"type": "git", "type": "git",
@ -13,7 +13,7 @@
"Gulpfile.js" "Gulpfile.js"
], ],
"dependencies": { "dependencies": {
"react": "^0.14.7 || ^15.0.0" "react": "^0.13.1"
}, },
"keywords": [ "keywords": [
"react", "react",

9
build/index.html Normal file
View File

@ -0,0 +1,9 @@
<html>
<head>
<title>Formsy Test</title>
</head>
<body>
<div id="app"></div>
<script src="build.js"></script>
</body>
</html>

55
build/test.js Normal file
View File

@ -0,0 +1,55 @@
var React = require('react');
var ReactDOM = require('react-dom');
var Formsy = require('./../src/main.js');
var Input = React.createClass({
onChange: function (event) {
this.props.setValue(event.currentTarget.value);
},
render: function () {
return (
<div>
{this.props.showRequired() ? 'required' : ''}
<input disabled={this.props.isFormDisabled()} value={this.props.getValue()} onChange={this.onChange}/>
</div>
);
}
});
Input = Formsy.HOC(Input);
var SomeComp = React.createClass({
getInitialState: function () {
return {
isRequired: false
};
},
toggleRequired: function () {
this.setState({
isRequired: !this.state.isRequired
});
},
render: function () {
return (
<div>
<Input name="foo[0]" value={''} validations="isEmail" validationError="No email" required={this.state.isRequired}/>
<button onClick={this.toggleRequired}>Test</button>
</div>
)
}
});
var FormApp = React.createClass({
onSubmit: function (model) {
console.log('model', model);
},
render: function () {
return (
<Formsy.Form ref="form" onSubmit={this.onSubmit}>
<SomeComp/>
</Formsy.Form>
);
}
});
ReactDOM.render(<FormApp />, document.getElementById('app'));

View File

@ -71,7 +71,7 @@ const DynamicInput = React.createClass({
return ( return (
<div className={className}> <div className={className}>
<label htmlFor={this.props.name}>{this.props.title}</label> <label htmlFor={this.props.name}>{this.props.title}</label>
<input type='text' name={this.props.name} onChange={this.changeValue} value={this.getValue() || ''}/> <input type='text' name={this.props.name} onChange={this.changeValue} value={this.getValue()}/>
<span className='validation-error'>{errorMessage}</span> <span className='validation-error'>{errorMessage}</span>
<Validations validationType={this.state.validationType} changeValidation={this.changeValidation}/> <Validations validationType={this.state.validationType} changeValidation={this.changeValidation}/>
</div> </div>

View File

@ -7,6 +7,15 @@ import MySelect from './../components/Select';
import MyRadioGroup from './../components/RadioGroup'; import MyRadioGroup from './../components/RadioGroup';
import MyMultiCheckboxSet from './../components/MultiCheckboxSet'; import MyMultiCheckboxSet from './../components/MultiCheckboxSet';
const validationErrors = {
'isEmail': 'The field must contain a valid email address',
'isNumeric': 'The field must contain only numbers',
'isAlphanumeric': 'The field must only contain alpha-numeric characters',
'equals': 'The field must be equal to {0}',
'minLength': 'The field must be at least {0} characters in length',
'maxLength': 'The field must not exceed {0} characters in length'
};
const Fields = props => { const Fields = props => {
function onRemove(pos) { function onRemove(pos) {
return event => { return event => {
@ -23,11 +32,11 @@ const Fields = props => {
field.type === 'input' ? field.type === 'input' ?
( (
<MyInput <MyInput
value=""
name={`fields[${i}]`} name={`fields[${i}]`}
title={field.validations ? JSON.stringify(field.validations) : 'No validations'} title={field.validations ? JSON.stringify(field.validations) : 'No validations'}
required={field.required} required={field.required}
validations={field.validations} validations={field.validations}
validationErrors={validationErrors}
/> />
) : ) :
( (
@ -36,6 +45,7 @@ const Fields = props => {
title={field.validations ? JSON.stringify(field.validations) : 'No validations'} title={field.validations ? JSON.stringify(field.validations) : 'No validations'}
required={field.required} required={field.required}
validations={field.validations} validations={field.validations}
validationErrors={validationErrors}
options={[ options={[
{title: '123', value: '123'}, {title: '123', value: '123'},
{title: 'some long text', value: 'some long text'}, {title: 'some long text', value: 'some long text'},
@ -87,7 +97,6 @@ const App = React.createClass({
cmp={(a, b) => JSON.stringify(a) === JSON.stringify(b)} cmp={(a, b) => JSON.stringify(a) === JSON.stringify(b)}
items={[ items={[
{isEmail: true}, {isEmail: true},
{isEmptyString: true},
{isNumeric: true}, {isNumeric: true},
{isAlphanumeric: true}, {isAlphanumeric: true},
{equals: 5}, {equals: 5},

View File

@ -20,8 +20,8 @@ const App = React.createClass({
render() { render() {
return ( return (
<Form onSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton} className="login"> <Form onSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton} className="login">
<MyInput value="" name="email" title="Email" validations="isEmail" validationError="This is not a valid email" required /> <MyInput name="email" title="Email" validations="isEmail" validationError="This is not a valid email" required />
<MyInput value="" name="password" title="Password" type="password" required /> <MyInput name="password" title="Password" type="password" required />
<button type="submit" disabled={!this.state.canSubmit}>Submit</button> <button type="submit" disabled={!this.state.canSubmit}>Submit</button>
</Form> </Form>
); );

View File

@ -1,6 +1,6 @@
{ {
"name": "formsy-react", "name": "formsy-react",
"version": "0.19.5", "version": "0.17.0",
"description": "A form input builder and validator for React JS", "description": "A form input builder and validator for React JS",
"repository": { "repository": {
"type": "git", "type": "git",
@ -8,7 +8,8 @@
}, },
"main": "lib/main.js", "main": "lib/main.js",
"scripts": { "scripts": {
"build": "NODE_ENV=production webpack -p --config webpack.production.config.js", "start": "webpack-dev-server --content-base build",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js",
"test": "babel-node testrunner", "test": "babel-node testrunner",
"examples": "webpack-dev-server --config examples/webpack.config.js --content-base examples", "examples": "webpack-dev-server --config examples/webpack.config.js --content-base examples",
"prepublish": "babel ./src/ -d ./lib/" "prepublish": "babel ./src/ -d ./lib/"
@ -23,27 +24,24 @@
"react-component" "react-component"
], ],
"dependencies": { "dependencies": {
"form-data-to-object": "^0.2.0" "form-data-to-object": "^0.1.0"
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.6.5", "babel": "^5.6.4",
"babel-loader": "^6.2.4", "babel-core": "^5.1.11",
"babel-preset-es2015": "^6.6.0", "babel-loader": "^5.0.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-2": "^6.5.0",
"create-react-class": "^15.6.0",
"jsdom": "^6.5.1", "jsdom": "^6.5.1",
"lolex": "^1.3.2",
"nodeunit": "^0.9.1", "nodeunit": "^0.9.1",
"prop-types": "^15.5.10", "react": "^0.14.0-rc1",
"react": "^15.0.0", "react-addons-pure-render-mixin": "^0.14.2",
"react-addons-pure-render-mixin": "^15.0.0", "react-addons-test-utils": "^0.14.0-rc1",
"react-addons-test-utils": "^15.0.0", "react-dom": "^0.14.0-rc1",
"react-dom": "^15.0.0", "sinon": "^1.17.1",
"sinon": "^1.17.3", "webpack": "^1.7.3",
"webpack": "^1.12.14", "webpack-dev-server": "^1.7.0"
"webpack-dev-server": "^1.14.1"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^0.14.0 || ^15.0.0" "react": "^0.14.0"
} }
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
release/formsy-react.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,9 +1,8 @@
var React = global.React || require('react'); var React = global.React || require('react');
var createReactClass = require('create-react-class');
var Mixin = require('./Mixin.js'); var Mixin = require('./Mixin.js');
module.exports = function () { module.exports = function () {
return function (Component) { return function (Component) {
return createReactClass({ return React.createClass({
mixins: [Mixin], mixins: [Mixin],
render: function () { render: function () {
return React.createElement(Component, { return React.createElement(Component, {

View File

@ -1,14 +1,10 @@
var React = global.React || require('react'); var React = global.React || require('react');
var createReactClass = require('create-react-class');
var Mixin = require('./Mixin.js'); var Mixin = require('./Mixin.js');
module.exports = function (Component) { module.exports = function (Component) {
return createReactClass({ return React.createClass({
displayName: 'Formsy(' + getDisplayName(Component) + ')',
mixins: [Mixin], mixins: [Mixin],
render: function () { render: function () {
const { innerRef } = this.props; return React.createElement(Component, {
const propsForElement = {
setValidations: this.setValidations, setValidations: this.setValidations,
setValue: this.setValue, setValue: this.setValue,
resetValue: this.resetValue, resetValue: this.resetValue,
@ -25,20 +21,7 @@ module.exports = function (Component) {
showError: this.showError, showError: this.showError,
isValidValue: this.isValidValue, isValidValue: this.isValidValue,
...this.props ...this.props
}; });
if (innerRef) {
propsForElement.ref = innerRef;
}
return React.createElement(Component, propsForElement);
} }
}); });
}; };
function getDisplayName(Component) {
return (
Component.displayName ||
Component.name ||
(typeof Component === 'string' ? Component : 'Component')
);
}

View File

@ -1,4 +1,3 @@
var PropTypes = require('prop-types');
var utils = require('./utils.js'); var utils = require('./utils.js');
var React = global.React || require('react'); var React = global.React || require('react');
@ -45,7 +44,7 @@ module.exports = {
}; };
}, },
contextTypes: { contextTypes: {
formsy: PropTypes.object // What about required? formsy: React.PropTypes.object // What about required?
}, },
getDefaultProps: function () { getDefaultProps: function () {
return { return {

View File

@ -1,6 +1,4 @@
var PropTypes = require('prop-types');
var React = global.React || require('react'); var React = global.React || require('react');
var createReactClass = require('create-react-class');
var Formsy = {}; var Formsy = {};
var validationRules = require('./validationRules.js'); var validationRules = require('./validationRules.js');
var formDataToObject = require('form-data-to-object'); var formDataToObject = require('form-data-to-object');
@ -23,7 +21,7 @@ Formsy.addValidationRule = function (name, func) {
validationRules[name] = func; validationRules[name] = func;
}; };
Formsy.Form = createReactClass({ Formsy.Form = React.createClass({
displayName: 'Formsy', displayName: 'Formsy',
getInitialState: function () { getInitialState: function () {
return { return {
@ -39,6 +37,7 @@ Formsy.Form = createReactClass({
onSubmit: function () {}, onSubmit: function () {},
onValidSubmit: function () {}, onValidSubmit: function () {},
onInvalidSubmit: function () {}, onInvalidSubmit: function () {},
onSubmitted: function () {},
onValid: function () {}, onValid: function () {},
onInvalid: function () {}, onInvalid: function () {},
onChange: function () {}, onChange: function () {},
@ -48,7 +47,7 @@ Formsy.Form = createReactClass({
}, },
childContextTypes: { childContextTypes: {
formsy: PropTypes.object formsy: React.PropTypes.object
}, },
getChildContext: function () { getChildContext: function () {
return { return {
@ -119,7 +118,7 @@ Formsy.Form = createReactClass({
if (this.props.mapping) { if (this.props.mapping) {
return this.props.mapping(model) return this.props.mapping(model)
} else { } else {
return formDataToObject.toObj(Object.keys(model).reduce((mappedModel, key) => { return formDataToObject(Object.keys(model).reduce((mappedModel, key) => {
var keyArray = key.split('.'); var keyArray = key.split('.');
var base = mappedModel; var base = mappedModel;
@ -143,7 +142,7 @@ Formsy.Form = createReactClass({
resetModel: function (data) { resetModel: function (data) {
this.inputs.forEach(component => { this.inputs.forEach(component => {
var name = component.props.name; var name = component.props.name;
if (data && data.hasOwnProperty(name)) { if (data && data[name]) {
component.setValue(data[name]); component.setValue(data[name]);
} else { } else {
component.resetValue(); component.resetValue();
@ -256,7 +255,7 @@ Formsy.Form = createReactClass({
// the component defines an explicit validate function // the component defines an explicit validate function
if (typeof component.validate === "function") { if (typeof component.validate === "function") {
validationResults.failed = component.validate() ? [] : ['failed']; validationResults.failed = component.validate() ? [] : [{ method: 'failed' }];
} }
var isRequired = Object.keys(component._requiredValidations).length ? !!requiredResults.success.length : false; var isRequired = Object.keys(component._requiredValidations).length ? !!requiredResults.success.length : false;
@ -286,7 +285,13 @@ Formsy.Form = createReactClass({
if (validationResults.failed.length) { if (validationResults.failed.length) {
return validationResults.failed.map(function(failed) { return validationResults.failed.map(function(failed) {
return validationErrors[failed] ? validationErrors[failed] : validationError; var errorMessage = validationErrors[failed.method] ? validationErrors[failed.method] : validationError;
failed.args && [].concat(failed.args).forEach((arg, i) => {
errorMessage = errorMessage.replace(new RegExp('\\{' + i + '\\}', 'g'), arg);
});
return errorMessage;
}).filter(function(x, pos, arr) { }).filter(function(x, pos, arr) {
// Remove duplicates // Remove duplicates
return arr.indexOf(x) === pos; return arr.indexOf(x) === pos;
@ -320,9 +325,9 @@ Formsy.Form = createReactClass({
var validation = validations[validationMethod](currentValues, value); var validation = validations[validationMethod](currentValues, value);
if (typeof validation === 'string') { if (typeof validation === 'string') {
results.errors.push(validation); results.errors.push(validation);
results.failed.push(validationMethod); results.failed.push({ method: validationMethod });
} else if (!validation) { } else if (!validation) {
results.failed.push(validationMethod); results.failed.push({ method: validationMethod });
} }
return; return;
@ -330,9 +335,9 @@ Formsy.Form = createReactClass({
var validation = validationRules[validationMethod](currentValues, value, validations[validationMethod]); var validation = validationRules[validationMethod](currentValues, value, validations[validationMethod]);
if (typeof validation === 'string') { if (typeof validation === 'string') {
results.errors.push(validation); results.errors.push(validation);
results.failed.push(validationMethod); results.failed.push({ method: validationMethod, args: validations[validationMethod] });
} else if (!validation) { } else if (!validation) {
results.failed.push(validationMethod); results.failed.push({ method: validationMethod, args: validations[validationMethod] });
} else { } else {
results.success.push(validationMethod); results.success.push(validationMethod);
} }
@ -394,7 +399,7 @@ Formsy.Form = createReactClass({
// If there are no inputs, set state where form is ready to trigger // If there are no inputs, set state where form is ready to trigger
// change event. New inputs might be added later // change event. New inputs might be added later
if (!this.inputs.length) { if (!this.inputs.length && this.isMounted()) {
this.setState({ this.setState({
canChange: true canChange: true
}); });
@ -425,24 +430,9 @@ Formsy.Form = createReactClass({
this.validateForm(); this.validateForm();
}, },
render: function () { render: function () {
var {
mapping,
validationErrors,
onSubmit,
onValid,
onValidSubmit,
onInvalid,
onInvalidSubmit,
onChange,
reset,
preventExternalInvalidation,
onSuccess,
onError,
...nonFormsyProps
} = this.props;
return ( return (
<form {...nonFormsyProps} onSubmit={this.submit}> <form {...this.props} onSubmit={this.submit}>
{this.props.children} {this.props.children}
</form> </form>
); );

View File

@ -30,10 +30,8 @@ module.exports = {
isSame: function (a, b) { isSame: function (a, b) {
if (typeof a !== typeof b) { if (typeof a !== typeof b) {
return false; return false;
} else if (Array.isArray(a) && Array.isArray(b)) { } else if (Array.isArray(a)) {
return !this.arraysDiffer(a, b); return !this.arraysDiffer(a, b);
} else if (typeof a === 'function') {
return a.toString() === b.toString();
} else if (typeof a === 'object' && a !== null && b !== null) { } else if (typeof a === 'object' && a !== null && b !== null) {
return !this.objectsDiffer(a, b); return !this.objectsDiffer(a, b);
} }

View File

@ -399,6 +399,39 @@ export default {
}, },
'should validation parameters passed to validation errors messages': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="A"
validations={{
'minLength': 3,
'maxLength': 5
}}
validationErrors={{
'minLength': 'The field must be at least {0} characters in length',
'maxLength': 'The field must not exceed {0} characters in length'
}}
/>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
TestUtils.Simulate.change(input, {target: {value: 'xx'}});
test.equal(inputComponent.getErrorMessage(), 'The field must be at least 3 characters in length');
TestUtils.Simulate.change(input, {target: {value: 'xxxxxx'}});
test.equal(inputComponent.getErrorMessage(), 'The field must not exceed 5 characters in length');
test.done();
},
'should not be valid if it is required and required rule is true': function (test) { 'should not be valid if it is required and required rule is true': function (test) {
const TestForm = React.createClass({ const TestForm = React.createClass({

View File

@ -4,30 +4,12 @@ import TestUtils from 'react-addons-test-utils';
import Formsy from './..'; import Formsy from './..';
import TestInput from './utils/TestInput'; import TestInput from './utils/TestInput';
import TestInputHoc from './utils/TestInputHoc';
import immediate from './utils/immediate'; import immediate from './utils/immediate';
import sinon from 'sinon'; import sinon from 'sinon';
export default { export default {
'Setting up a form': { 'Setting up a form': {
'should expose the users DOM node through an innerRef prop': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInputHoc name="name" innerRef={(c) => { this.name = c; }} />
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = form.name;
test.equal(input.methodOnWrappedInstance('foo'), 'foo');
test.done();
},
'should render a form into the document': function (test) { 'should render a form into the document': function (test) {
@ -368,7 +350,7 @@ export default {
}, },
'should trigger onChange once when form element is changed': function (test) { 'should trigger onChange when form element is changed': function (test) {
const hasChanged = sinon.spy(); const hasChanged = sinon.spy();
const form = TestUtils.renderIntoDocument( const form = TestUtils.renderIntoDocument(
@ -377,12 +359,12 @@ export default {
</Formsy.Form> </Formsy.Form>
); );
TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}}); TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}});
test.equal(hasChanged.calledOnce, true); test.equal(hasChanged.called, true);
test.done(); test.done();
}, },
'should trigger onChange once when new input is added to form': function (test) { 'should trigger onChange when new input is added to form': function (test) {
const hasChanged = sinon.spy(); const hasChanged = sinon.spy();
const TestForm = React.createClass({ const TestForm = React.createClass({
@ -412,7 +394,7 @@ export default {
const form = TestUtils.renderIntoDocument(<TestForm/>); const form = TestUtils.renderIntoDocument(<TestForm/>);
form.addInput(); form.addInput();
immediate(() => { immediate(() => {
test.equal(hasChanged.calledOnce, true); test.equal(hasChanged.called, true);
test.done(); test.done();
}); });
@ -668,30 +650,6 @@ export default {
}, },
'should be able to reset the form to empty values': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" value="42" type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
formsyForm.reset({
foo: ''
});
test.equal(input.getValue(), '');
test.done();
},
'.isChanged()': { '.isChanged()': {
'initially returns false': function (test) { 'initially returns false': function (test) {

View File

@ -42,15 +42,6 @@ export default {
}, },
'should fail when a string\'s length is smaller': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue="my"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with empty string': function (test) { 'should pass with empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue=""/>); const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue=""/>);

View File

@ -23,13 +23,8 @@ export default {
test.equal(utils.isSame(objG, objH), true); test.equal(utils.isSame(objG, objH), true);
test.equal(utils.isSame(objA, objH), false); test.equal(utils.isSame(objA, objH), false);
test.equal(utils.isSame(objC, objH), false);
test.equal(utils.isSame(objG, objA), false); test.equal(utils.isSame(objG, objA), false);
test.equal(utils.isSame(() => {}, () => {}), true);
test.equal(utils.isSame(objA, () => {}), false);
test.equal(utils.isSame(() => {}, objA), false);
test.done(); test.done();
} }

View File

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import Formsy from './../..'; import Formsy from './../..';
import assign from 'react/lib/Object.assign';
const defaultProps = { const defaultProps = {
mixins: [Formsy.Mixin], mixins: [Formsy.Mixin],
@ -15,7 +16,7 @@ const defaultProps = {
}; };
export function InputFactory(props) { export function InputFactory(props) {
return React.createClass(Object.assign(defaultProps, props)); return React.createClass(assign(defaultProps, props));
} }
export default React.createClass(defaultProps); export default React.createClass(defaultProps);

View File

@ -1,13 +0,0 @@
import React from 'react';
import { HOC as formsyHoc } from './../..';
const defaultProps = {
methodOnWrappedInstance(param) {
return param;
},
render() {
return (<input />);
},
};
export default formsyHoc(React.createClass(defaultProps));

21
webpack.config.js Normal file
View File

@ -0,0 +1,21 @@
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: path.resolve(__dirname, 'build', 'test.js'),
output: {
path: path.resolve(__dirname, 'build'),
filename: 'build.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.json$/, loader: 'json' }
]
}
};