Compare commits
1 Commits
master
...
validation
| Author | SHA1 | Date |
|---|---|---|
|
|
231ac4c7de |
|
|
@ -1,2 +1,4 @@
|
|||
.DS_Store
|
||||
build
|
||||
node_modules
|
||||
lib
|
||||
|
|
|
|||
11
.npmignore
11
.npmignore
|
|
@ -1,8 +1,3 @@
|
|||
.babelrc
|
||||
.editorconfig
|
||||
.travis.yml
|
||||
testrunner.js
|
||||
webpack.production.config.js
|
||||
examples/
|
||||
release/
|
||||
tests/
|
||||
build/
|
||||
bower.json
|
||||
Gulpfile.js
|
||||
70
API.md
70
API.md
|
|
@ -1,5 +1,6 @@
|
|||
# API
|
||||
|
||||
- [Formsy.defaults - DEPRECATED](#formsydefaults)
|
||||
- [Formsy.Form](#formsyform)
|
||||
- [className](#classname)
|
||||
- [mapping](#mapping)
|
||||
|
|
@ -12,20 +13,20 @@
|
|||
- [onChange()](#onchange)
|
||||
- [reset()](#resetform)
|
||||
- [getModel()](#getmodel)
|
||||
- [updateInputsWithError()](#updateinputswitherrorerrors)
|
||||
- [updateInputsWithError()](#updateinputswitherror)
|
||||
- [preventExternalInvalidation](#preventexternalinvalidation)
|
||||
- [Formsy.Mixin](#formsymixin)
|
||||
- [name](#name)
|
||||
- [value](#value)
|
||||
- [validations](#validations)
|
||||
- [validationError](#validationerror)
|
||||
- [validationErrors](#validationerrors-1)
|
||||
- [validationErrors](#validationerrors)
|
||||
- [required](#required)
|
||||
- [getValue()](#getvalue)
|
||||
- [setValue()](#setvalue)
|
||||
- [hasValue() - DEPRECATED](#hasvalue)
|
||||
- [resetValue()](#resetvalue)
|
||||
- [getErrorMessage()](#geterrormessage)
|
||||
- [getErrorMessages()](#geterrormessages)
|
||||
- [isValid()](#isvalid)
|
||||
- [isValidValue()](#isvalidvalue)
|
||||
- [isRequired()](#isrequired)
|
||||
|
|
@ -37,11 +38,12 @@
|
|||
- [validate](#validate)
|
||||
- [formNoValidate](#formnovalidate)
|
||||
- [Formsy.HOC](#formsyhoc)
|
||||
- [innerRef](#innerRef)
|
||||
- [Formsy.Decorator](#formsydecorator)
|
||||
- [Formsy.addValidationRule](#formsyaddvalidationrule)
|
||||
- [Validators](#validators)
|
||||
|
||||
### <a name="formsydefaults">Formsy.defaults(options) - DEPRECATED</a>
|
||||
|
||||
### <a name="formsyform">Formsy.Form</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
|
||||
<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"
|
||||
validations={{
|
||||
isEmail: true,
|
||||
maxLength: 50
|
||||
maxLength: 50,
|
||||
someCustomValidation: [1, 2, 3]
|
||||
}}
|
||||
validationErrors={{
|
||||
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.
|
||||
|
||||
#### <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>
|
||||
```jsx
|
||||
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**.
|
||||
|
||||
#### <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>
|
||||
```jsx
|
||||
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
|
||||
import {HOC} from 'formsy-react';
|
||||
|
||||
class MyInputHoc extends React.Component {
|
||||
class MyInput extends React.Component {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
|
|
@ -576,26 +596,7 @@ class MyInputHoc extends React.Component {
|
|||
);
|
||||
}
|
||||
};
|
||||
export default HOC(MyInputHoc);
|
||||
```
|
||||
|
||||
#### <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>
|
||||
);
|
||||
}
|
||||
})
|
||||
export default HOC(MyInput);
|
||||
```
|
||||
|
||||
### <a name="formsydecorator">Formsy.Decorator</a>
|
||||
|
|
@ -624,7 +625,7 @@ Formsy.addValidationRule('isFruit', function (values, value) {
|
|||
});
|
||||
```
|
||||
```jsx
|
||||
<MyInputComponent name="fruit" validations="isFruit"/>
|
||||
<MyInputComponent name="fruit" validations="'isFruit"/>
|
||||
```
|
||||
Another example:
|
||||
```jsx
|
||||
|
|
@ -657,8 +658,6 @@ Formsy.addValidationRule('isMoreThan', function (values, value, otherField) {
|
|||
```
|
||||
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
|
||||
<MyInputComponent name="foo" validations="isEmail"/>
|
||||
|
|
@ -766,8 +765,7 @@ Returns true if the value length is the equal.
|
|||
```jsx
|
||||
<MyInputComponent name="number" validations="minLength:1"/>
|
||||
```
|
||||
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.
|
||||
Return true if the value is more or equal to argument
|
||||
|
||||
**maxLength:length**
|
||||
```jsx
|
||||
|
|
|
|||
2
LICENSE
2
LICENSE
|
|
@ -1,6 +1,6 @@
|
|||
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
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
65
README.md
65
README.md
|
|
@ -6,6 +6,8 @@ A form input builder and validator for React JS
|
|||
| [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>
|
||||
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
|
||||
|
||||
```jsx
|
||||
import Formsy from 'formsy-react';
|
||||
|
||||
const MyAppForm = React.createClass({
|
||||
getInitialState() {
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
var Formsy = require('formsy-react');
|
||||
var MyAppForm = React.createClass({
|
||||
getInitialState: function () {
|
||||
return {
|
||||
canSubmit: false
|
||||
}
|
||||
},
|
||||
enableButton() {
|
||||
enableButton: function () {
|
||||
this.setState({
|
||||
canSubmit: true
|
||||
});
|
||||
},
|
||||
disableButton() {
|
||||
disableButton: function () {
|
||||
this.setState({
|
||||
canSubmit: false
|
||||
});
|
||||
},
|
||||
submit(model) {
|
||||
submit: function (model) {
|
||||
someDep.saveEmail(model.email);
|
||||
},
|
||||
render() {
|
||||
render: function () {
|
||||
return (
|
||||
<Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}>
|
||||
<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".
|
||||
|
||||
#### Building a form element (required)
|
||||
```jsx
|
||||
import Formsy from 'formsy-react';
|
||||
|
||||
const MyOwnInput = React.createClass({
|
||||
```javascript
|
||||
/** @jsx React.DOM */
|
||||
var Formsy = require('formsy-react');
|
||||
var MyOwnInput = React.createClass({
|
||||
|
||||
// Add the Formsy Mixin
|
||||
mixins: [Formsy.Mixin],
|
||||
|
||||
// setValue() will set the value of the component, which in
|
||||
// turn will validate it and the rest of the form
|
||||
changeValue(event) {
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
render: function () {
|
||||
|
||||
render() {
|
||||
// Set a specific className based on the validation
|
||||
// state of this component. showRequired() is true
|
||||
// when the value is empty and the required prop is
|
||||
// passed to the input. showError() is true when the
|
||||
// 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
|
||||
// or the server has returned an error message
|
||||
const errorMessage = this.getErrorMessage();
|
||||
var errorMessage = this.getErrorMessage();
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
|
|
@ -128,11 +130,32 @@ The form element component is what gives the form validation functionality to wh
|
|||
## Contribute
|
||||
- Fork repo
|
||||
- `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
|
||||
|
||||
## 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.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "formsy-react",
|
||||
"version": "0.18.0",
|
||||
"version": "0.16.0",
|
||||
"description": "A form input builder and validator for React JS",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
|
@ -13,7 +13,7 @@
|
|||
"Gulpfile.js"
|
||||
],
|
||||
"dependencies": {
|
||||
"react": "^0.14.7 || ^15.0.0"
|
||||
"react": "^0.13.1"
|
||||
},
|
||||
"keywords": [
|
||||
"react",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>Formsy Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="build.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -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'));
|
||||
|
|
@ -71,7 +71,7 @@ const DynamicInput = React.createClass({
|
|||
return (
|
||||
<div className={className}>
|
||||
<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>
|
||||
<Validations validationType={this.state.validationType} changeValidation={this.changeValidation}/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -7,6 +7,15 @@ import MySelect from './../components/Select';
|
|||
import MyRadioGroup from './../components/RadioGroup';
|
||||
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 => {
|
||||
function onRemove(pos) {
|
||||
return event => {
|
||||
|
|
@ -23,11 +32,11 @@ const Fields = props => {
|
|||
field.type === 'input' ?
|
||||
(
|
||||
<MyInput
|
||||
value=""
|
||||
name={`fields[${i}]`}
|
||||
title={field.validations ? JSON.stringify(field.validations) : 'No validations'}
|
||||
required={field.required}
|
||||
validations={field.validations}
|
||||
validationErrors={validationErrors}
|
||||
/>
|
||||
) :
|
||||
(
|
||||
|
|
@ -36,6 +45,7 @@ const Fields = props => {
|
|||
title={field.validations ? JSON.stringify(field.validations) : 'No validations'}
|
||||
required={field.required}
|
||||
validations={field.validations}
|
||||
validationErrors={validationErrors}
|
||||
options={[
|
||||
{title: '123', value: '123'},
|
||||
{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)}
|
||||
items={[
|
||||
{isEmail: true},
|
||||
{isEmptyString: true},
|
||||
{isNumeric: true},
|
||||
{isAlphanumeric: true},
|
||||
{equals: 5},
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@ const App = React.createClass({
|
|||
render() {
|
||||
return (
|
||||
<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 value="" name="password" title="Password" type="password" required />
|
||||
<MyInput name="email" title="Email" validations="isEmail" validationError="This is not a valid email" required />
|
||||
<MyInput name="password" title="Password" type="password" required />
|
||||
<button type="submit" disabled={!this.state.canSubmit}>Submit</button>
|
||||
</Form>
|
||||
);
|
||||
|
|
|
|||
34
package.json
34
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "formsy-react",
|
||||
"version": "0.19.5",
|
||||
"version": "0.17.0",
|
||||
"description": "A form input builder and validator for React JS",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
|
@ -8,7 +8,8 @@
|
|||
},
|
||||
"main": "lib/main.js",
|
||||
"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",
|
||||
"examples": "webpack-dev-server --config examples/webpack.config.js --content-base examples",
|
||||
"prepublish": "babel ./src/ -d ./lib/"
|
||||
|
|
@ -23,27 +24,24 @@
|
|||
"react-component"
|
||||
],
|
||||
"dependencies": {
|
||||
"form-data-to-object": "^0.2.0"
|
||||
"form-data-to-object": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-cli": "^6.6.5",
|
||||
"babel-loader": "^6.2.4",
|
||||
"babel-preset-es2015": "^6.6.0",
|
||||
"babel-preset-react": "^6.5.0",
|
||||
"babel-preset-stage-2": "^6.5.0",
|
||||
"create-react-class": "^15.6.0",
|
||||
"babel": "^5.6.4",
|
||||
"babel-core": "^5.1.11",
|
||||
"babel-loader": "^5.0.0",
|
||||
"jsdom": "^6.5.1",
|
||||
"lolex": "^1.3.2",
|
||||
"nodeunit": "^0.9.1",
|
||||
"prop-types": "^15.5.10",
|
||||
"react": "^15.0.0",
|
||||
"react-addons-pure-render-mixin": "^15.0.0",
|
||||
"react-addons-test-utils": "^15.0.0",
|
||||
"react-dom": "^15.0.0",
|
||||
"sinon": "^1.17.3",
|
||||
"webpack": "^1.12.14",
|
||||
"webpack-dev-server": "^1.14.1"
|
||||
"react": "^0.14.0-rc1",
|
||||
"react-addons-pure-render-mixin": "^0.14.2",
|
||||
"react-addons-test-utils": "^0.14.0-rc1",
|
||||
"react-dom": "^0.14.0-rc1",
|
||||
"sinon": "^1.17.1",
|
||||
"webpack": "^1.7.3",
|
||||
"webpack-dev-server": "^1.7.0"
|
||||
},
|
||||
"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
File diff suppressed because one or more lines are too long
|
|
@ -1,9 +1,8 @@
|
|||
var React = global.React || require('react');
|
||||
var createReactClass = require('create-react-class');
|
||||
var Mixin = require('./Mixin.js');
|
||||
module.exports = function () {
|
||||
return function (Component) {
|
||||
return createReactClass({
|
||||
return React.createClass({
|
||||
mixins: [Mixin],
|
||||
render: function () {
|
||||
return React.createElement(Component, {
|
||||
|
|
|
|||
23
src/HOC.js
23
src/HOC.js
|
|
@ -1,14 +1,10 @@
|
|||
var React = global.React || require('react');
|
||||
var createReactClass = require('create-react-class');
|
||||
var Mixin = require('./Mixin.js');
|
||||
module.exports = function (Component) {
|
||||
return createReactClass({
|
||||
displayName: 'Formsy(' + getDisplayName(Component) + ')',
|
||||
return React.createClass({
|
||||
mixins: [Mixin],
|
||||
|
||||
render: function () {
|
||||
const { innerRef } = this.props;
|
||||
const propsForElement = {
|
||||
return React.createElement(Component, {
|
||||
setValidations: this.setValidations,
|
||||
setValue: this.setValue,
|
||||
resetValue: this.resetValue,
|
||||
|
|
@ -25,20 +21,7 @@ module.exports = function (Component) {
|
|||
showError: this.showError,
|
||||
isValidValue: this.isValidValue,
|
||||
...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')
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
var PropTypes = require('prop-types');
|
||||
var utils = require('./utils.js');
|
||||
var React = global.React || require('react');
|
||||
|
||||
|
|
@ -45,7 +44,7 @@ module.exports = {
|
|||
};
|
||||
},
|
||||
contextTypes: {
|
||||
formsy: PropTypes.object // What about required?
|
||||
formsy: React.PropTypes.object // What about required?
|
||||
},
|
||||
getDefaultProps: function () {
|
||||
return {
|
||||
|
|
|
|||
48
src/main.js
48
src/main.js
|
|
@ -1,6 +1,4 @@
|
|||
var PropTypes = require('prop-types');
|
||||
var React = global.React || require('react');
|
||||
var createReactClass = require('create-react-class');
|
||||
var Formsy = {};
|
||||
var validationRules = require('./validationRules.js');
|
||||
var formDataToObject = require('form-data-to-object');
|
||||
|
|
@ -23,7 +21,7 @@ Formsy.addValidationRule = function (name, func) {
|
|||
validationRules[name] = func;
|
||||
};
|
||||
|
||||
Formsy.Form = createReactClass({
|
||||
Formsy.Form = React.createClass({
|
||||
displayName: 'Formsy',
|
||||
getInitialState: function () {
|
||||
return {
|
||||
|
|
@ -39,6 +37,7 @@ Formsy.Form = createReactClass({
|
|||
onSubmit: function () {},
|
||||
onValidSubmit: function () {},
|
||||
onInvalidSubmit: function () {},
|
||||
onSubmitted: function () {},
|
||||
onValid: function () {},
|
||||
onInvalid: function () {},
|
||||
onChange: function () {},
|
||||
|
|
@ -48,7 +47,7 @@ Formsy.Form = createReactClass({
|
|||
},
|
||||
|
||||
childContextTypes: {
|
||||
formsy: PropTypes.object
|
||||
formsy: React.PropTypes.object
|
||||
},
|
||||
getChildContext: function () {
|
||||
return {
|
||||
|
|
@ -119,7 +118,7 @@ Formsy.Form = createReactClass({
|
|||
if (this.props.mapping) {
|
||||
return this.props.mapping(model)
|
||||
} else {
|
||||
return formDataToObject.toObj(Object.keys(model).reduce((mappedModel, key) => {
|
||||
return formDataToObject(Object.keys(model).reduce((mappedModel, key) => {
|
||||
|
||||
var keyArray = key.split('.');
|
||||
var base = mappedModel;
|
||||
|
|
@ -143,7 +142,7 @@ Formsy.Form = createReactClass({
|
|||
resetModel: function (data) {
|
||||
this.inputs.forEach(component => {
|
||||
var name = component.props.name;
|
||||
if (data && data.hasOwnProperty(name)) {
|
||||
if (data && data[name]) {
|
||||
component.setValue(data[name]);
|
||||
} else {
|
||||
component.resetValue();
|
||||
|
|
@ -256,7 +255,7 @@ Formsy.Form = createReactClass({
|
|||
|
||||
// the component defines an explicit 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;
|
||||
|
|
@ -286,7 +285,13 @@ Formsy.Form = createReactClass({
|
|||
|
||||
if (validationResults.failed.length) {
|
||||
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) {
|
||||
// Remove duplicates
|
||||
return arr.indexOf(x) === pos;
|
||||
|
|
@ -320,9 +325,9 @@ Formsy.Form = createReactClass({
|
|||
var validation = validations[validationMethod](currentValues, value);
|
||||
if (typeof validation === 'string') {
|
||||
results.errors.push(validation);
|
||||
results.failed.push(validationMethod);
|
||||
results.failed.push({ method: validationMethod });
|
||||
} else if (!validation) {
|
||||
results.failed.push(validationMethod);
|
||||
results.failed.push({ method: validationMethod });
|
||||
}
|
||||
return;
|
||||
|
||||
|
|
@ -330,9 +335,9 @@ Formsy.Form = createReactClass({
|
|||
var validation = validationRules[validationMethod](currentValues, value, validations[validationMethod]);
|
||||
if (typeof validation === 'string') {
|
||||
results.errors.push(validation);
|
||||
results.failed.push(validationMethod);
|
||||
results.failed.push({ method: validationMethod, args: validations[validationMethod] });
|
||||
} else if (!validation) {
|
||||
results.failed.push(validationMethod);
|
||||
results.failed.push({ method: validationMethod, args: validations[validationMethod] });
|
||||
} else {
|
||||
results.success.push(validationMethod);
|
||||
}
|
||||
|
|
@ -394,7 +399,7 @@ Formsy.Form = createReactClass({
|
|||
|
||||
// If there are no inputs, set state where form is ready to trigger
|
||||
// change event. New inputs might be added later
|
||||
if (!this.inputs.length) {
|
||||
if (!this.inputs.length && this.isMounted()) {
|
||||
this.setState({
|
||||
canChange: true
|
||||
});
|
||||
|
|
@ -425,24 +430,9 @@ Formsy.Form = createReactClass({
|
|||
this.validateForm();
|
||||
},
|
||||
render: function () {
|
||||
var {
|
||||
mapping,
|
||||
validationErrors,
|
||||
onSubmit,
|
||||
onValid,
|
||||
onValidSubmit,
|
||||
onInvalid,
|
||||
onInvalidSubmit,
|
||||
onChange,
|
||||
reset,
|
||||
preventExternalInvalidation,
|
||||
onSuccess,
|
||||
onError,
|
||||
...nonFormsyProps
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<form {...nonFormsyProps} onSubmit={this.submit}>
|
||||
<form {...this.props} onSubmit={this.submit}>
|
||||
{this.props.children}
|
||||
</form>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -30,10 +30,8 @@ module.exports = {
|
|||
isSame: function (a, b) {
|
||||
if (typeof a !== typeof b) {
|
||||
return false;
|
||||
} else if (Array.isArray(a) && Array.isArray(b)) {
|
||||
} else if (Array.isArray(a)) {
|
||||
return !this.arraysDiffer(a, b);
|
||||
} else if (typeof a === 'function') {
|
||||
return a.toString() === b.toString();
|
||||
} else if (typeof a === 'object' && a !== null && b !== null) {
|
||||
return !this.objectsDiffer(a, b);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
||||
const TestForm = React.createClass({
|
||||
|
|
|
|||
|
|
@ -4,30 +4,12 @@ import TestUtils from 'react-addons-test-utils';
|
|||
|
||||
import Formsy from './..';
|
||||
import TestInput from './utils/TestInput';
|
||||
import TestInputHoc from './utils/TestInputHoc';
|
||||
import immediate from './utils/immediate';
|
||||
import sinon from 'sinon';
|
||||
|
||||
export default {
|
||||
|
||||
'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) {
|
||||
|
||||
|
|
@ -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 form = TestUtils.renderIntoDocument(
|
||||
|
|
@ -377,12 +359,12 @@ export default {
|
|||
</Formsy.Form>
|
||||
);
|
||||
TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}});
|
||||
test.equal(hasChanged.calledOnce, true);
|
||||
test.equal(hasChanged.called, true);
|
||||
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 TestForm = React.createClass({
|
||||
|
|
@ -412,7 +394,7 @@ export default {
|
|||
const form = TestUtils.renderIntoDocument(<TestForm/>);
|
||||
form.addInput();
|
||||
immediate(() => {
|
||||
test.equal(hasChanged.calledOnce, true);
|
||||
test.equal(hasChanged.called, true);
|
||||
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()': {
|
||||
|
||||
'initially returns false': function (test) {
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
||||
const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue=""/>);
|
||||
|
|
|
|||
|
|
@ -23,13 +23,8 @@ export default {
|
|||
|
||||
test.equal(utils.isSame(objG, objH), true);
|
||||
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(() => {}, () => {}), true);
|
||||
test.equal(utils.isSame(objA, () => {}), false);
|
||||
test.equal(utils.isSame(() => {}, objA), false);
|
||||
|
||||
test.done();
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React from 'react';
|
||||
import Formsy from './../..';
|
||||
import assign from 'react/lib/Object.assign';
|
||||
|
||||
const defaultProps = {
|
||||
mixins: [Formsy.Mixin],
|
||||
|
|
@ -15,7 +16,7 @@ const defaultProps = {
|
|||
};
|
||||
|
||||
export function InputFactory(props) {
|
||||
return React.createClass(Object.assign(defaultProps, props));
|
||||
return React.createClass(assign(defaultProps, props));
|
||||
}
|
||||
|
||||
export default React.createClass(defaultProps);
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
|
@ -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' }
|
||||
]
|
||||
}
|
||||
|
||||
};
|
||||
Loading…
Reference in New Issue