├── .babelrc
├── .editorconfig
├── .gitignore
├── .npmignore
├── .travis.yml
├── API.md
├── CHANGES.md
├── LICENSE
├── README.md
├── bower.json
├── examples
├── README.md
├── components
│ ├── Input.js
│ ├── MultiCheckboxSet.js
│ ├── RadioGroup.js
│ └── Select.js
├── custom-validation
│ ├── app.css
│ ├── app.js
│ └── index.html
├── dynamic-form-fields
│ ├── app.css
│ ├── app.js
│ └── index.html
├── global.css
├── index.html
├── login
│ ├── app.css
│ ├── app.js
│ └── index.html
├── reset-values
│ ├── app.css
│ ├── app.js
│ └── index.html
└── webpack.config.js
├── package.json
├── release
├── formsy-react.js
└── formsy-react.js.map
├── src
├── Decorator.js
├── HOC.js
├── Mixin.js
├── main.js
├── utils.js
└── validationRules.js
├── testrunner.js
├── tests
├── Element-spec.js
├── Formsy-spec.js
├── Rules-equals-spec.js
├── Rules-isAlpha-spec.js
├── Rules-isAlphanumeric-spec.js
├── Rules-isEmail-spec.js
├── Rules-isEmptyString-spec.js
├── Rules-isExisty-spec.js
├── Rules-isFloat-spec.js
├── Rules-isInt-spec.js
├── Rules-isLength-spec.js
├── Rules-isNumeric-spec.js
├── Rules-isUrl-spec.js
├── Rules-isWords-spec.js
├── Rules-maxLength-spec.js
├── Rules-minLength-spec.js
├── Utils-spec.js
├── Validation-spec.js
└── utils
│ ├── TestInput.js
│ ├── TestInputHoc.js
│ └── immediate.js
└── webpack.production.config.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "react",
4 | "es2015",
5 | "stage-2"
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | end_of_line = lf
7 | charset = utf-8
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | lib
3 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .babelrc
2 | .editorconfig
3 | .travis.yml
4 | testrunner.js
5 | webpack.production.config.js
6 | examples/
7 | release/
8 | tests/
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | sudo: false
3 | node_js:
4 | - '4.1'
5 |
--------------------------------------------------------------------------------
/API.md:
--------------------------------------------------------------------------------
1 | # API
2 |
3 | - [Formsy.Form](#formsyform)
4 | - [className](#classname)
5 | - [mapping](#mapping)
6 | - [validationErrors](#validationerrors)
7 | - [onSubmit()](#onsubmit)
8 | - [onValid()](#onvalid)
9 | - [onInvalid()](#oninvalid)
10 | - [onValidSubmit()](#onvalidsubmit)
11 | - [onInvalidSubmit()](#oninvalidsubmit)
12 | - [onChange()](#onchange)
13 | - [reset()](#resetform)
14 | - [getModel()](#getmodel)
15 | - [updateInputsWithError()](#updateinputswitherrorerrors)
16 | - [preventExternalInvalidation](#preventexternalinvalidation)
17 | - [Formsy.Mixin](#formsymixin)
18 | - [name](#name)
19 | - [value](#value)
20 | - [validations](#validations)
21 | - [validationError](#validationerror)
22 | - [validationErrors](#validationerrors-1)
23 | - [required](#required)
24 | - [getValue()](#getvalue)
25 | - [setValue()](#setvalue)
26 | - [resetValue()](#resetvalue)
27 | - [getErrorMessage()](#geterrormessage)
28 | - [getErrorMessages()](#geterrormessages)
29 | - [isValid()](#isvalid)
30 | - [isValidValue()](#isvalidvalue)
31 | - [isRequired()](#isrequired)
32 | - [showRequired()](#showrequired)
33 | - [showError()](#showerror)
34 | - [isPristine()](#ispristine)
35 | - [isFormDisabled()](#isformdisabled)
36 | - [isFormSubmitted()](#isformsubmitted)
37 | - [validate](#validate)
38 | - [formNoValidate](#formnovalidate)
39 | - [Formsy.HOC](#formsyhoc)
40 | - [innerRef](#innerRef)
41 | - [Formsy.Decorator](#formsydecorator)
42 | - [Formsy.addValidationRule](#formsyaddvalidationrule)
43 | - [Validators](#validators)
44 |
45 | ### Formsy.Form
46 |
47 | #### className
48 | ```jsx
49 |
50 | ```
51 | Sets a class name on the form itself.
52 |
53 | #### mapping
54 | ```jsx
55 | var MyForm = React.createClass({
56 | mapInputs: function (inputs) {
57 | return {
58 | 'field1': inputs.foo,
59 | 'field2': inputs.bar
60 | };
61 | },
62 | submit: function (model) {
63 | model; // {field1: '', field2: ''}
64 | },
65 | render: function () {
66 | return (
67 |
68 |
69 |
70 |
71 | );
72 | }
73 | })
74 | ```
75 | Use mapping to change the data structure of your input elements. This structure is passed to the submit hooks.
76 |
77 | #### validationErrors
78 | You can manually pass down errors to your form. In combination with `onChange` you are able to validate using an external validator.
79 |
80 | ```jsx
81 | var Form = React.createClass({
82 | getInitialState: function () {
83 | return {
84 | validationErrors: {}
85 | };
86 | },
87 | validateForm: function (values) {
88 | if (!values.foo) {
89 | this.setState({
90 | validationErrors: {
91 | foo: 'Has no value'
92 | }
93 | });
94 | } else {
95 | this.setState({
96 | validationErrors: {}
97 | });
98 | }
99 | },
100 | render: function () {
101 | return (
102 |
103 |
104 |
105 | );
106 | }
107 | });
108 | ```
109 |
110 | #### onSubmit(data, resetForm, invalidateForm)
111 | ```jsx
112 |
113 | ```
114 | Takes a function to run when the submit button has been clicked.
115 |
116 | 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.
117 |
118 | #### onValid()
119 | ```jsx
120 |
121 | ```
122 | Whenever the form becomes valid the "onValid" handler is called. Use it to change state of buttons or whatever your heart desires.
123 |
124 | #### onInvalid()
125 | ```jsx
126 |
127 | ```
128 | Whenever the form becomes invalid the "onInvalid" handler is called. Use it to for example revert "onValid" state.
129 |
130 | #### onValidSubmit(model, resetForm, invalidateForm)
131 | ```jsx
132 |
133 | ```
134 | Triggers when form is submitted with a valid state. The arguments are the same as on `onSubmit`.
135 |
136 | #### onInvalidSubmit(model, resetForm, invalidateForm)
137 | ```jsx
138 |
139 | ```
140 | Triggers when form is submitted with an invalid state. The arguments are the same as on `onSubmit`.
141 |
142 | #### onChange(currentValues, isChanged)
143 | ```jsx
144 |
145 | ```
146 | "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.
147 |
148 | #### reset(values)
149 | ```jsx
150 | var MyForm = React.createClass({
151 | resetForm: function () {
152 | this.refs.form.reset();
153 | },
154 | render: function () {
155 | return (
156 |
157 | ...
158 |
159 | );
160 | }
161 | });
162 | ```
163 | 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.
164 |
165 | #### getModel()
166 | ```jsx
167 | var MyForm = React.createClass({
168 | getMyData: function () {
169 | alert(this.refs.form.getModel());
170 | },
171 | render: function () {
172 | return (
173 |
174 | ...
175 |
176 | );
177 | }
178 | });
179 | ```
180 | Manually get values from all registered components. Keys are name of input and value is of course the value.
181 |
182 | #### updateInputsWithError(errors)
183 | ```jsx
184 | var MyForm = React.createClass({
185 | someFunction: function () {
186 | this.refs.form.updateInputsWithError({
187 | email: 'This email is taken',
188 | 'field[10]': 'Some error!'
189 | });
190 | },
191 | render: function () {
192 | return (
193 |
194 | ...
195 |
196 | );
197 | }
198 | });
199 | ```
200 | 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`](#onsubmitdata-resetform-invalidateform), [`onValidSubmit`](#onvalidsubmitmodel-resetform-invalidateform) or [`onInvalidSubmit`](#oninvalidsubmitmodel-resetform-invalidateform).
201 |
202 | #### preventExternalInvalidation
203 | ```jsx
204 | var MyForm = React.createClass({
205 | onSubmit: function (model, reset, invalidate) {
206 | invalidate({
207 | foo: 'Got some error'
208 | });
209 | },
210 | render: function () {
211 | return (
212 |
213 | ...
214 |
215 | );
216 | }
217 | });
218 | ```
219 | With the `preventExternalInvalidation` the input will not be invalidated though it has an error.
220 |
221 | ### Formsy.Mixin
222 |
223 | #### name
224 | ```jsx
225 |
226 |
227 | ```
228 | 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'}}`.
229 |
230 | #### value
231 | ```jsx
232 |
233 | ```
234 | 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.
235 |
236 | #### validations
237 | ```jsx
238 |
239 |
240 |
244 |
251 | ```
252 | 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:
253 |
254 | ```jsx
255 |
256 |
257 | ```
258 | Works just fine.
259 |
260 | #### validationError
261 | ```jsx
262 |
263 | ```
264 | The message that will show when the form input component is invalid. It will be used as a default error.
265 |
266 | #### validationErrors
267 | ```jsx
268 |
279 | ```
280 | 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.
281 |
282 | #### required
283 | ```jsx
284 |
285 | ```
286 |
287 | 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.
288 |
289 | ```jsx
290 |
291 | ```
292 | Would be typical for a checkbox type of form element that must be checked, e.g. agreeing to Terms of Service.
293 |
294 | #### getValue()
295 | ```jsx
296 | var MyInput = React.createClass({
297 | mixins: [Formsy.Mixin],
298 | render: function () {
299 | return (
300 |
301 | );
302 | }
303 | });
304 | ```
305 | Gets the current value of the form input component.
306 |
307 | #### setValue(value)
308 | ```jsx
309 | var MyInput = React.createClass({
310 | mixins: [Formsy.Mixin],
311 | changeValue: function (event) {
312 | this.setValue(event.currentTarget.value);
313 | },
314 | render: function () {
315 | return (
316 |
317 | );
318 | }
319 | });
320 | ```
321 | 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.
322 |
323 | #### resetValue()
324 | ```jsx
325 | var MyInput = React.createClass({
326 | mixins: [Formsy.Mixin],
327 | changeValue: function (event) {
328 | this.setValue(event.currentTarget.value);
329 | },
330 | render: function () {
331 | return (
332 |
333 |
334 | Reset
335 |
336 | );
337 | }
338 | });
339 | ```
340 | Resets to empty value. This will run a **setState()** on the component and do a render.
341 |
342 | #### getErrorMessage()
343 | ```jsx
344 | var MyInput = React.createClass({
345 | mixins: [Formsy.Mixin],
346 | changeValue: function (event) {
347 | this.setValue(event.currentTarget.value);
348 | },
349 | render: function () {
350 | return (
351 |
352 |
353 | {this.getErrorMessage()}
354 |
355 | );
356 | }
357 | });
358 | ```
359 | Will return the validation message set if the form input component is invalid. If form input component is valid it returns **null**.
360 |
361 | #### getErrorMessages()
362 | Will return the validation messages set if the form input component is invalid. If form input component is valid it returns empty array.
363 |
364 | #### isValid()
365 | ```jsx
366 | var MyInput = React.createClass({
367 | mixins: [Formsy.Mixin],
368 | changeValue: function (event) {
369 | this.setValue(event.currentTarget.value);
370 | },
371 | render: function () {
372 | var face = this.isValid() ? ':-)' : ':-(';
373 | return (
374 |
375 | {face}
376 |
377 | {this.getErrorMessage()}
378 |
379 | );
380 | }
381 | });
382 | ```
383 | Returns the valid state of the form input component.
384 |
385 | #### isValidValue()
386 | You can pre-verify a value against the passed validators to the form element.
387 |
388 | ```jsx
389 | var MyInput = React.createClass({
390 | mixins: [Formsy.Mixin],
391 | changeValue: function (event) {
392 | if (this.isValidValue(event.target.value)) {
393 | this.setValue(event.target.value);
394 | }
395 | },
396 | render: function () {
397 | return ;
398 | }
399 | });
400 |
401 | var MyForm = React.createClass({
402 | render: function () {
403 | return (
404 |
405 |
406 |
407 | );
408 | }
409 | });
410 | ```
411 |
412 | #### isRequired()
413 | ```jsx
414 | var MyInput = React.createClass({
415 | mixins: [Formsy.Mixin],
416 | changeValue: function (event) {
417 | this.setValue(event.currentTarget.value);
418 | },
419 | render: function () {
420 | return (
421 |
422 | {this.props.label} {this.isRequired() ? '*' : null}
423 |
424 | {this.getErrorMessage()}
425 |
426 | );
427 | }
428 | });
429 | ```
430 | Returns true if the required property has been passed.
431 |
432 | #### showRequired()
433 | ```jsx
434 | var MyInput = React.createClass({
435 | mixins: [Formsy.Mixin],
436 | changeValue: function (event) {
437 | this.setValue(event.currentTarget.value);
438 | },
439 | render: function () {
440 | var className = this.showRequired() ? 'required' : '';
441 | return (
442 |
443 |
444 | {this.getErrorMessage()}
445 |
446 | );
447 | }
448 | });
449 | ```
450 | 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.
451 |
452 | #### showError()
453 | ```jsx
454 | var MyInput = React.createClass({
455 | mixins: [Formsy.Mixin],
456 | changeValue: function (event) {
457 | this.setValue(event.currentTarget.value);
458 | },
459 | render: function () {
460 | var className = this.showRequired() ? 'required' : this.showError() ? 'error' : '';
461 | return (
462 |
463 |
464 | {this.getErrorMessage()}
465 |
466 | );
467 | }
468 | });
469 | ```
470 | 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.
471 |
472 | #### isPristine()
473 | ```jsx
474 | var MyInput = React.createClass({
475 | mixins: [Formsy.Mixin],
476 | changeValue: function (event) {
477 | this.setValue(event.currentTarget.value);
478 | },
479 | render: function () {
480 | return (
481 |
482 |
483 | {this.isPristine() ? 'You have not touched this yet' : ''}
484 |
485 | );
486 | }
487 | });
488 | ```
489 | By default all formsy input elements are pristine, which means they are not "touched". As soon as the [**setValue**](#setvaluevalue) method is run it will no longer be pristine.
490 |
491 | **note!** When the form is reset, using the resetForm callback function on for example [**onSubmit**](#onsubmitdata-resetform-invalidateform) the inputs are reset to their pristine state.
492 |
493 | #### isFormDisabled()
494 | ```jsx
495 | var MyInput = React.createClass({
496 | mixins: [Formsy.Mixin],
497 | render: function () {
498 | return (
499 |
500 |
501 |
502 | );
503 | }
504 | });
505 |
506 | React.render();
507 | ```
508 | You can now disable the form itself with a prop and use **isFormDisabled()** inside form elements to verify this prop.
509 |
510 | #### isFormSubmitted()
511 | ```jsx
512 | var MyInput = React.createClass({
513 | mixins: [Formsy.Mixin],
514 | render: function () {
515 | var error = this.isFormSubmitted() ? this.getErrorMessage() : null;
516 | return (
517 |
518 |
519 | {error}
520 |
521 | );
522 | }
523 | });
524 | ```
525 | You can check if the form has been submitted.
526 |
527 | #### validate
528 | ```jsx
529 | var MyInput = React.createClass({
530 | mixins: [Formsy.Mixin],
531 | changeValue: function (event) {
532 | this.setValue(event.target.value);
533 | },
534 | validate: function () {
535 | return !!this.getValue();
536 | },
537 | render: function () {
538 | return (
539 |
540 |
541 |
542 | );
543 | }
544 | });
545 |
546 | React.render();
547 | ```
548 | You can create custom validation inside a form element. The validate method defined will be run when you set new values to the form element. It will also be run when the form validates itself. This is an alternative to passing in validation rules as props.
549 |
550 | #### formNoValidate
551 | To avoid native validation behavior on inputs, use the React `formNoValidate` property.
552 | ```jsx
553 | var MyInput = React.createClass({
554 | mixins: [Formsy.Mixin],
555 | render: function () {
556 | return (
557 |
558 |
559 |
560 | );
561 | }
562 | });
563 | ```
564 |
565 | ### Formsy.HOC
566 | The same methods as the mixin are exposed to the HOC version of the element component, though through the `props`, not on the instance.
567 | ```jsx
568 | import {HOC} from 'formsy-react';
569 |
570 | class MyInputHoc extends React.Component {
571 | render() {
572 | return (
573 |
574 | this.props.setValue(e.target.value)}/>
575 |
576 | );
577 | }
578 | };
579 | export default HOC(MyInputHoc);
580 | ```
581 |
582 | #### innerRef
583 |
584 | Use an `innerRef` prop to get a reference to your DOM node.
585 |
586 | ```jsx
587 | var MyForm = React.createClass({
588 | componentDidMount() {
589 | this.searchInput.focus()
590 | },
591 | render: function () {
592 | return (
593 |
594 | { this.searchInput = c; }} />
595 |
596 | );
597 | }
598 | })
599 | ```
600 |
601 | ### Formsy.Decorator
602 | The same methods as the mixin are exposed to the decorator version of the element component, though through the `props`, not on the instance.
603 | ```jsx
604 | import {Decorator as FormsyElement} from 'formsy-react';
605 |
606 | @FormsyElement()
607 | class MyInput extends React.Component {
608 | render() {
609 | return (
610 |
611 | this.props.setValue(e.target.value)}/>
612 |
613 | );
614 | }
615 | };
616 | export default MyInput
617 | ```
618 |
619 | ### Formsy.addValidationRule(name, ruleFunc)
620 | An example:
621 | ```jsx
622 | Formsy.addValidationRule('isFruit', function (values, value) {
623 | return ['apple', 'orange', 'pear'].indexOf(value) >= 0;
624 | });
625 | ```
626 | ```jsx
627 |
628 | ```
629 | Another example:
630 | ```jsx
631 | Formsy.addValidationRule('isIn', function (values, value, array) {
632 | return array.indexOf(value) >= 0;
633 | });
634 | ```
635 | ```jsx
636 |
637 | ```
638 | Cross input validation:
639 | ```jsx
640 | Formsy.addValidationRule('isMoreThan', function (values, value, otherField) {
641 | // The this context points to an object containing the values
642 | // {childAge: "", parentAge: "5"}
643 | // otherField argument is from the validations rule ("childAge")
644 | return Number(value) > Number(values[otherField]);
645 | });
646 | ```
647 | ```jsx
648 |
649 |
650 | ```
651 | ## Validators
652 | **matchRegexp**
653 | ```jsx
654 |
657 | ```
658 | Returns true if the value is thruthful
659 |
660 | _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._
661 |
662 | **isEmail**
663 | ```jsx
664 |
665 | ```
666 | Return true if it is an email
667 |
668 | **isUrl**
669 | ```jsx
670 |
671 | ```
672 | Return true if it is an url
673 |
674 | **isExisty**
675 | ```jsx
676 |
677 | ```
678 | Returns true if the value is not undefined or null
679 |
680 | **isUndefined**
681 | ```jsx
682 |
683 | ```
684 | Returns true if the value is the undefined
685 |
686 | **isEmptyString**
687 | ```jsx
688 |
689 | ```
690 | Returns true if the value is an empty string
691 |
692 | **isTrue**
693 | ```jsx
694 |
695 | ```
696 | Returns true if the value is the boolean true
697 |
698 | **isFalse**
699 | ```jsx
700 |
701 | ```
702 | Returns true if the value is the boolean false
703 |
704 | **isAlpha**
705 | ```jsx
706 |
707 | ```
708 | Returns true if string is only letters
709 |
710 | **isNumeric**
711 | ```jsx
712 |
713 | ```
714 | Returns true if string only contains numbers. Examples: 42; -3.14
715 |
716 | **isAlphanumeric**
717 | ```jsx
718 |
719 | ```
720 | Returns true if string only contains letters or numbers
721 |
722 | **isInt**
723 | ```jsx
724 |
725 | ```
726 | Returns true if string represents integer value. Examples: 42; -12; 0
727 |
728 | **isFloat**
729 | ```jsx
730 |
731 | ```
732 | Returns true if string represents float value. Examples: 42; -3.14; 1e3
733 |
734 | **isWords**
735 | ```jsx
736 |
737 | ```
738 | Returns true if string is only letters, including spaces and tabs
739 |
740 | **isSpecialWords**
741 | ```jsx
742 |
743 | ```
744 | Returns true if string is only letters, including special letters (a-z,ú,ø,æ,å)
745 |
746 | **equals:value**
747 | ```jsx
748 |
749 | ```
750 | Return true if the value from input component matches value passed (==).
751 |
752 | **equalsField:fieldName**
753 | ```jsx
754 |
755 |
756 | ```
757 | Return true if the value from input component matches value passed (==).
758 |
759 | **isLength:length**
760 | ```jsx
761 |
762 | ```
763 | Returns true if the value length is the equal.
764 |
765 | **minLength:length**
766 | ```jsx
767 |
768 | ```
769 | Return true if the value is more or equal to argument.
770 | **Also returns true for an empty value.** If you want to get false, then you should use [`required`](#required) additionally.
771 |
772 | **maxLength:length**
773 | ```jsx
774 |
775 | ```
776 | Return true if the value is less or equal to argument
777 |
--------------------------------------------------------------------------------
/CHANGES.md:
--------------------------------------------------------------------------------
1 | This is the old CHANGES file. Please look at [releases](https://github.com/christianalfoni/formsy-react/releases) for latest changes.
2 |
3 | **0.8.0**
4 | - Fixed bug where dynamic form elements gave "not mounted" error (Thanks @sdemjanenko)
5 | - React is now a peer dependency (Thanks @snario)
6 | - Dynamically updated values should now work with initial "undefined" value (Thanks @sdemjanenko)
7 | - Validations are now dynamic. Change the prop and existing values are re-validated (thanks @bryannaegele)
8 | - You can now set a "disabled" prop on the form and check "isFormDisabled()" in form elements
9 | - Refactored some code and written a couple of tests
10 |
11 | **0.7.2**:
12 | - isNumber validation now supports float (Thanks @hahahana)
13 | - Form XHR calls now includes CSRF headers, if exists (Thanks @hahahana)
14 |
15 | **0.7.1**
16 | - Fixed bug where external update of value on pristine form element did not update the form model (Thanks @sdemjanenko)
17 | - Fixed bug where children are null/undefined (Thanks @sdemjanenko)
18 |
19 | **0.7.0**
20 | - Dynamic form elements. Add them at any point and they will be registered with the form
21 | - **onChange()** handler is called whenever an form element has changed its value or a new form element is added to the form
22 | - isNumeric validator now also handles actual numbers, not only strings
23 | - Some more tests
24 |
25 | **0.6.0**
26 | - **onSubmit()** now has the same signature regardless of passing url attribute or not
27 | - **isPristine()** is a new method to handle "touched" form elements (thanks @FoxxMD)
28 | - Mapping attributes to pass a function that maps input values to new structure. The new structure is either passed to *onSubmit* and/or to the server when using a url attribute (thanks for feedback @MattAitchison)
29 | - Added default "equalsField" validation rule
30 | - Lots of tests!
31 |
32 | **0.5.2**
33 | - Fixed bug with handlers in ajax requests (Thanks @smokku)
34 |
35 | **0.5.1**
36 | - Fixed bug with empty validations
37 |
38 | **0.5.0**
39 | - Added [cross input validation](#formsyaddvalidationrule)
40 | - Fixed bug where validation rule refers to a string
41 | - Added "invalidateForm" function when manually submitting the form
42 |
43 | **0.4.1**
44 | - Fixed bug where form element is required, but no validations
45 |
46 | **0.4.0**:
47 | - Possibility to handle form data manually using "onSubmit"
48 | - Added two more default rules. *isWords* and *isSpecialWords*
49 |
50 | **0.3.0**:
51 | - Deprecated everything related to buttons automatically added
52 | - Added onValid and onInvalid handlers, use those to manipulate submit buttons etc.
53 |
54 | **0.2.3**:
55 |
56 | - Fixed bug where child does not have props property
57 |
58 | **0.2.2**:
59 |
60 | - Fixed bug with updating the props
61 |
62 | **0.2.1**:
63 |
64 | - Cancel button displays if onCancel handler is defined
65 |
66 | **0.2.0**:
67 |
68 | - Implemented hasValue() method
69 |
70 | **0.1.3**:
71 |
72 | - Fixed resetValue bug
73 |
74 | **0.1.2**:
75 |
76 | - Fixed isValue check to empty string, needs to support false and 0
77 |
78 | **0.1.1**:
79 |
80 | - Added resetValue method
81 | - Changed value check of showRequired
82 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014-2016 PatientSky A/S
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Moved!
2 |
3 | This project has moved. Starting from 1.0.0 onward, develeopment will continue
4 | at https://github.com/formsy/formsy-react/
5 |
6 | ---
7 |
8 | formsy-react [](https://github.com/christianalfoni/formsy-react/releases) [](https://travis-ci.org/christianalfoni/formsy-react)
9 | ============
10 |
11 | A form input builder and validator for React JS
12 |
13 | | [How to use](#how-to-use) | [API](/API.md) | [Examples](/examples) |
14 | |---|---|---|
15 |
16 | ## Background
17 | 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.
18 |
19 | The main concept is that forms, inputs and validation is done very differently across developers and projects. This extension to React JS aims to be that "sweet spot" between flexibility and reusability.
20 |
21 | ## What you can do
22 |
23 | 1. Build any kind of form element components. Not just traditional inputs, but anything you want and get that validation for free
24 |
25 | 2. Add validation rules and use them with simple syntax
26 |
27 | 3. Use handlers for different states of your form. Ex. "onSubmit", "onError", "onValid" etc.
28 |
29 | 4. Pass external errors to the form to invalidate elements
30 |
31 | 5. You can dynamically add form elements to your form and they will register/unregister to the form
32 |
33 | ## Default elements
34 | You can look at examples in this repo or use the [formsy-react-components](https://github.com/twisty/formsy-react-components) project to use bootstrap with formsy-react, or use [formsy-material-ui](https://github.com/mbrookes/formsy-material-ui) to use [Material-UI](http://material-ui.com/) with formsy-react.
35 |
36 | ## Install
37 |
38 | 1. Download from this REPO and use globally (Formsy) or with requirejs
39 | 2. Install with `npm install formsy-react` and use with browserify etc.
40 | 3. Install with `bower install formsy-react`
41 |
42 | ## Changes
43 |
44 | [Check out releases](https://github.com/christianalfoni/formsy-react/releases)
45 |
46 | [Older changes](CHANGES.md)
47 |
48 | ## How to use
49 |
50 | See [`examples` folder](/examples) for examples. [Codepen demo](http://codepen.io/semigradsky/pen/dYYpwv?editors=001).
51 |
52 | Complete API reference is available [here](/API.md).
53 |
54 | #### Formsy gives you a form straight out of the box
55 |
56 | ```jsx
57 | import Formsy from 'formsy-react';
58 |
59 | const MyAppForm = React.createClass({
60 | getInitialState() {
61 | return {
62 | canSubmit: false
63 | }
64 | },
65 | enableButton() {
66 | this.setState({
67 | canSubmit: true
68 | });
69 | },
70 | disableButton() {
71 | this.setState({
72 | canSubmit: false
73 | });
74 | },
75 | submit(model) {
76 | someDep.saveEmail(model.email);
77 | },
78 | render() {
79 | return (
80 |
81 |
82 | Submit
83 |
84 | );
85 | }
86 | });
87 | ```
88 |
89 | 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".
90 |
91 | #### Building a form element (required)
92 | ```jsx
93 | import Formsy from 'formsy-react';
94 |
95 | const MyOwnInput = React.createClass({
96 |
97 | // Add the Formsy Mixin
98 | mixins: [Formsy.Mixin],
99 |
100 | // setValue() will set the value of the component, which in
101 | // turn will validate it and the rest of the form
102 | changeValue(event) {
103 | this.setValue(event.currentTarget.value);
104 | },
105 |
106 | render() {
107 | // Set a specific className based on the validation
108 | // state of this component. showRequired() is true
109 | // when the value is empty and the required prop is
110 | // passed to the input. showError() is true when the
111 | // value typed is invalid
112 | const className = this.showRequired() ? 'required' : this.showError() ? 'error' : null;
113 |
114 | // An error message is returned ONLY if the component is invalid
115 | // or the server has returned an error message
116 | const errorMessage = this.getErrorMessage();
117 |
118 | return (
119 |
120 |
121 | {errorMessage}
122 |
123 | );
124 | }
125 | });
126 | ```
127 | The form element component is what gives the form validation functionality to whatever you want to put inside this wrapper. You do not have to use traditional inputs, it can be anything you want and the value of the form element can also be anything you want. As you can see it is very flexible, you just have a small API to help you identify the state of the component and set its value.
128 |
129 | ## Related projects
130 | - [formsy-material-ui](https://github.com/mbrookes/formsy-material-ui) - A formsy-react compatibility wrapper for [Material-UI](http://material-ui.com/) form components.
131 | - [formsy-react-components](https://github.com/twisty/formsy-react-components) - A set of React JS components for use in a formsy-react form.
132 | - ...
133 | - Send PR for adding your project to this list!
134 |
135 | ## Contribute
136 | - Fork repo
137 | - `npm install`
138 | - `npm run examples` runs the development server on `localhost:8080`
139 | - `npm test` runs the tests
140 |
141 | ## License
142 |
143 | [The MIT License (MIT)](/LICENSE)
144 |
145 | Copyright (c) 2014-2016 PatientSky A/S
146 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "formsy-react",
3 | "version": "0.18.0",
4 | "description": "A form input builder and validator for React JS",
5 | "repository": {
6 | "type": "git",
7 | "url": "https://github.com/christianalfoni/formsy-react.git"
8 | },
9 | "main": "src/main.js",
10 | "license": "MIT",
11 | "ignore": [
12 | "build/",
13 | "Gulpfile.js"
14 | ],
15 | "dependencies": {
16 | "react": "^0.14.7 || ^15.0.0"
17 | },
18 | "keywords": [
19 | "react",
20 | "form",
21 | "forms",
22 | "validation",
23 | "react-component"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | Formsy React Examples
2 | =====================
3 |
4 | To run and development examples:
5 |
6 | 1. Clone this repo
7 | 2. Run `npm install`
8 | 3. Start the development server with `npm run examples`
9 | 4. Point your browser to http://localhost:8080
10 |
11 |
12 | ## Possible Issues
13 |
14 | Examples might not run if you have an old node packages. Try clear [npm cache](https://docs.npmjs.com/cli/cache#details) and reinstall dependencies:
15 | ```
16 | rm -rf node_modules
17 | npm cache clean
18 | npm install
19 | npm run examples
20 | ```
21 |
22 | If it is not helped try update your node.js and npm.
23 |
24 | ## Examples
25 |
26 | 1. [**Login**](login)
27 |
28 | Two required fields with simple validation.
29 |
30 | 2. [**Custom Validation**](custom-validation)
31 |
32 | One field with added validation rule (`Formsy.addValidationRule`) and one field with dynamically added validation and error messages.
33 |
34 | 3. [**Reset Values**](reset-values)
35 |
36 | Reset text input, checkbox and select to their pristine values.
37 |
38 | 4. [**Dynamic Form Fields**](dynamic-form-fields)
39 |
40 | Dynamically adding and removing fields to form.
41 |
--------------------------------------------------------------------------------
/examples/components/Input.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Formsy from 'formsy-react';
3 |
4 | const MyInput = React.createClass({
5 |
6 | // Add the Formsy Mixin
7 | mixins: [Formsy.Mixin],
8 |
9 | // setValue() will set the value of the component, which in
10 | // turn will validate it and the rest of the form
11 | changeValue(event) {
12 | this.setValue(event.currentTarget[this.props.type === 'checkbox' ? 'checked' : 'value']);
13 | },
14 | render() {
15 |
16 | // Set a specific className based on the validation
17 | // state of this component. showRequired() is true
18 | // when the value is empty and the required prop is
19 | // passed to the input. showError() is true when the
20 | // value typed is invalid
21 | const className = 'form-group' + (this.props.className || ' ') +
22 | (this.showRequired() ? 'required' : this.showError() ? 'error' : '');
23 |
24 | // An error message is returned ONLY if the component is invalid
25 | // or the server has returned an error message
26 | const errorMessage = this.getErrorMessage();
27 |
28 | return (
29 |
30 | {this.props.title}
31 |
38 | {errorMessage}
39 |
40 | );
41 | }
42 | });
43 |
44 | export default MyInput;
45 |
--------------------------------------------------------------------------------
/examples/components/MultiCheckboxSet.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Formsy from 'formsy-react';
3 |
4 | function contains(container, item, cmp) {
5 | for (const it of container) {
6 | if (cmp(it, item)) {
7 | return true;
8 | }
9 | }
10 | return false;
11 | }
12 |
13 | const MyRadioGroup = React.createClass({
14 | mixins: [Formsy.Mixin],
15 | getInitialState() {
16 | return { value: [], cmp: (a, b) => a === b };
17 | },
18 | componentDidMount() {
19 | const value = this.props.value || [];
20 | this.setValue(value);
21 | this.setState({ value: value, cmp: this.props.cmp || this.state.cmp });
22 | },
23 |
24 | changeValue(value, event) {
25 | const checked = event.currentTarget.checked;
26 |
27 | let newValue = [];
28 | if (checked) {
29 | newValue = this.state.value.concat(value);
30 | } else {
31 | newValue = this.state.value.filter(it => !this.state.cmp(it, value));
32 | }
33 |
34 | this.setValue(newValue);
35 | this.setState({ value: newValue });
36 | },
37 |
38 | render() {
39 | const className = 'form-group' + (this.props.className || ' ') +
40 | (this.showRequired() ? 'required' : this.showError() ? 'error' : '');
41 | const errorMessage = this.getErrorMessage();
42 |
43 | const { name, title, items } = this.props;
44 | return (
45 |
46 |
{title}
47 | {items.map((item, i) => (
48 |
49 |
55 | {JSON.stringify(item)}
56 |
57 | ))
58 | }
59 |
{errorMessage}
60 |
61 | );
62 | }
63 |
64 | });
65 |
66 | export default MyRadioGroup;
67 |
--------------------------------------------------------------------------------
/examples/components/RadioGroup.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Formsy from 'formsy-react';
3 |
4 | const MyRadioGroup = React.createClass({
5 | mixins: [Formsy.Mixin],
6 |
7 | componentDidMount() {
8 | const value = this.props.value;
9 | this.setValue(value);
10 | this.setState({ value });
11 | },
12 |
13 | changeValue(value) {
14 | this.setValue(value);
15 | this.setState({ value });
16 | },
17 |
18 | render() {
19 | const className = 'form-group' + (this.props.className || ' ') +
20 | (this.showRequired() ? 'required' : this.showError() ? 'error' : '');
21 | const errorMessage = this.getErrorMessage();
22 |
23 | const { name, title, items } = this.props;
24 | return (
25 |
26 |
{title}
27 | {items.map((item, i) => (
28 |
29 |
35 | {item.toString()}
36 |
37 | ))
38 | }
39 |
{errorMessage}
40 |
41 | );
42 | }
43 |
44 | });
45 |
46 | export default MyRadioGroup;
47 |
--------------------------------------------------------------------------------
/examples/components/Select.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Formsy from 'formsy-react';
3 |
4 | const MySelect = React.createClass({
5 | mixins: [Formsy.Mixin],
6 |
7 | changeValue(event) {
8 | this.setValue(event.currentTarget.value);
9 | },
10 |
11 | render() {
12 | const className = 'form-group' + (this.props.className || ' ') +
13 | (this.showRequired() ? 'required' : this.showError() ? 'error' : '');
14 | const errorMessage = this.getErrorMessage();
15 |
16 | const options = this.props.options.map((option, i) => (
17 |
18 | {option.title}
19 |
20 | ));
21 |
22 | return (
23 |
24 | {this.props.title}
25 |
26 | {options}
27 |
28 | {errorMessage}
29 |
30 | );
31 | }
32 |
33 | });
34 |
35 | export default MySelect;
36 |
--------------------------------------------------------------------------------
/examples/custom-validation/app.css:
--------------------------------------------------------------------------------
1 | .custom-validation {
2 | width: 500px;
3 | margin: 0 auto;
4 | }
--------------------------------------------------------------------------------
/examples/custom-validation/app.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import Formsy from 'formsy-react';
4 |
5 | import MyInput from './../components/Input';
6 |
7 | const currentYear = new Date().getFullYear();
8 |
9 | const validators = {
10 | time: {
11 | regexp: /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/,
12 | message: 'Not valid time'
13 | },
14 | decimal: {
15 | regexp: /(^\d*\.?\d*[0-9]+\d*$)|(^[0-9]+\d*\.\d*$)/,
16 | message: 'Please type decimal value'
17 | },
18 | binary: {
19 | regexp: /^([0-1])*$/,
20 | message: '10101000'
21 | }
22 | };
23 |
24 | Formsy.addValidationRule('isYearOfBirth', (values, value) => {
25 | value = parseInt(value);
26 | if (typeof value !== 'number') {
27 | return false;
28 | }
29 | return value < currentYear && value > currentYear - 130;
30 | });
31 |
32 | const App = React.createClass({
33 | submit(data) {
34 | alert(JSON.stringify(data, null, 4));
35 | },
36 | render() {
37 | return (
38 |
39 |
40 |
41 | Submit
42 |
43 | );
44 | }
45 | });
46 |
47 | const DynamicInput = React.createClass({
48 | mixins: [Formsy.Mixin],
49 | getInitialState() {
50 | return { validationType: 'time' };
51 | },
52 | changeValue(event) {
53 | this.setValue(event.currentTarget.value);
54 | },
55 | changeValidation(validationType) {
56 | this.setState({ validationType: validationType });
57 | this.setValue(this.getValue());
58 | },
59 | validate() {
60 | const value = this.getValue();
61 | console.log(value, this.state.validationType);
62 | return value ? validators[this.state.validationType].regexp.test(value) : true;
63 | },
64 | getCustomErrorMessage() {
65 | return this.showError() ? validators[this.state.validationType].message : '';
66 | },
67 | render() {
68 | const className = 'form-group' + (this.props.className || ' ') + (this.showRequired() ? 'required' : this.showError() ? 'error' : null);
69 | const errorMessage = this.getCustomErrorMessage();
70 |
71 | return (
72 |
73 | {this.props.title}
74 |
75 | {errorMessage}
76 |
77 |
78 | );
79 | }
80 | });
81 |
82 | const Validations = React.createClass({
83 | changeValidation(e) {
84 | this.props.changeValidation(e.target.value);
85 | },
86 | render() {
87 | const { validationType } = this.props;
88 | return (
89 |
90 | Validation Type
91 |
92 | Time
93 |
94 |
95 | Decimal
96 |
97 |
98 | Binary
99 |
100 |
101 | );
102 | }
103 | });
104 |
105 | ReactDOM.render( , document.getElementById('example'));
106 |
--------------------------------------------------------------------------------
/examples/custom-validation/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Custom Validation Example
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/examples/dynamic-form-fields/app.css:
--------------------------------------------------------------------------------
1 | .many-fields-conf {
2 | width: 400px;
3 | margin: 0 auto;
4 | }
5 |
6 | .many-fields {
7 | width: 600px;
8 | margin: 0 auto;
9 | }
10 |
11 | .field {
12 | overflow: hidden;
13 | }
14 |
15 | .many-fields .form-group {
16 | width: calc(100% - 20px);
17 | float: left;
18 | }
19 | .many-fields .remove-field {
20 | margin-top: 30px;
21 | margin-left: 8px;
22 | display: inline-block;
23 | text-decoration: none;
24 | }
25 |
--------------------------------------------------------------------------------
/examples/dynamic-form-fields/app.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { Form } from 'formsy-react';
4 |
5 | import MyInput from './../components/Input';
6 | import MySelect from './../components/Select';
7 | import MyRadioGroup from './../components/RadioGroup';
8 | import MyMultiCheckboxSet from './../components/MultiCheckboxSet';
9 |
10 | const Fields = props => {
11 | function onRemove(pos) {
12 | return event => {
13 | event.preventDefault();
14 | props.onRemove(pos);
15 | };
16 | }
17 | const foo = 'required';
18 | return (
19 |
20 | {props.data.map((field, i) => (
21 |
22 | {
23 | field.type === 'input' ?
24 | (
25 |
32 | ) :
33 | (
34 |
47 | )
48 | }
49 |
X
50 |
51 | ))
52 | }
53 |
54 | );
55 | };
56 |
57 | const App = React.createClass({
58 | getInitialState() {
59 | return { fields: [], canSubmit: false };
60 | },
61 | submit(data) {
62 | alert(JSON.stringify(data, null, 4));
63 | },
64 | addField(fieldData) {
65 | fieldData.validations = fieldData.validations.length ?
66 | fieldData.validations.reduce((a, b) => Object.assign({}, a, b)) :
67 | null;
68 | fieldData.id = Date.now();
69 | this.setState({ fields: this.state.fields.concat(fieldData) });
70 | },
71 | removeField(pos) {
72 | const fields = this.state.fields;
73 | this.setState({ fields: fields.slice(0, pos).concat(fields.slice(pos+1)) })
74 | },
75 | enableButton() {
76 | this.setState({ canSubmit: true });
77 | },
78 | disableButton() {
79 | this.setState({ canSubmit: false });
80 | },
81 | render() {
82 | const { fields, canSubmit } = this.state;
83 | return (
84 |
85 |
104 |
108 |
109 | );
110 | }
111 | });
112 |
113 | ReactDOM.render( , document.getElementById('example'));
114 |
--------------------------------------------------------------------------------
/examples/dynamic-form-fields/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Dynamic Form Fields
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/global.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: "Helvetica Neue", Arial;
3 | font-weight: 200;
4 | }
5 |
6 | h1, h2, h3 {
7 | font-weight: 100;
8 | }
9 |
10 | a {
11 | color: hsl(200, 50%, 50%);
12 | }
13 |
14 | a.active {
15 | color: hsl(20, 50%, 50%);
16 | }
17 |
18 | .breadcrumbs a {
19 | text-decoration: none;
20 | }
21 |
22 | form {
23 | padding: 15px;
24 | border: 1px solid black;
25 | }
26 |
27 | .form-group {
28 | margin-bottom: 10px;
29 | }
30 |
31 | .form-group label {
32 | display: inline-block;
33 | max-width: 100%;
34 | margin-top: 5px;
35 | font-weight: 700;
36 | }
37 |
38 | .form-group input[type='text'],
39 | .form-group input[type='email'],
40 | .form-group input[type='number'],
41 | .form-group input[type='password'],
42 | .form-group select {
43 | display: block;
44 | width: 100%;
45 | height: 34px;
46 | padding: 6px 12px;
47 | font-size: 14px;
48 | line-height: 1.42857143;
49 | color: #555;
50 | background-color: #FFF;
51 | background-image: none;
52 | border: 2px solid #CCC;
53 | border-radius: 4px;
54 | box-sizing: border-box;
55 | }
56 |
57 | .form-group.error input[type='text'],
58 | .form-group.error input[type='email'],
59 | .form-group.error input[type='number'],
60 | .form-group.error input[type='password'],
61 | .form-group.error select {
62 | border-color: red;
63 | color: red;
64 | }
65 |
66 | .form-group.required input[type='text'],
67 | .form-group.required input[type='email'],
68 | .form-group.required input[type='number'],
69 | .form-group.required input[type='password'],
70 | .form-group.required select {
71 | border-color: #FF9696;
72 | }
73 |
74 | .validation-error {
75 | color: red;
76 | margin: 5px 0;
77 | display: inline-block;
78 | }
79 |
80 | button {
81 | padding: 10px 15px;
82 | border-radius: 4px;
83 | }
84 |
85 | .buttons button {
86 | margin-left: 10px;
87 | }
88 | .buttons button:first-child {
89 | margin-left: 0;
90 | }
91 |
--------------------------------------------------------------------------------
/examples/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Formsy React Examples
5 |
6 |
7 |
8 | Formsy React Examples
9 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/examples/login/app.css:
--------------------------------------------------------------------------------
1 | .login {
2 | width: 400px;
3 | margin: 0 auto;
4 | }
--------------------------------------------------------------------------------
/examples/login/app.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { Form } from 'formsy-react';
4 |
5 | import MyInput from './../components/Input';
6 |
7 | const App = React.createClass({
8 | getInitialState() {
9 | return { canSubmit: false };
10 | },
11 | submit(data) {
12 | alert(JSON.stringify(data, null, 4));
13 | },
14 | enableButton() {
15 | this.setState({ canSubmit: true });
16 | },
17 | disableButton() {
18 | this.setState({ canSubmit: false });
19 | },
20 | render() {
21 | return (
22 |
27 | );
28 | }
29 | });
30 |
31 | ReactDOM.render( , document.getElementById('example'));
32 |
--------------------------------------------------------------------------------
/examples/login/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Login Example
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/examples/reset-values/app.css:
--------------------------------------------------------------------------------
1 | .form {
2 | width: 400px;
3 | margin: 0 auto;
4 | }
5 |
--------------------------------------------------------------------------------
/examples/reset-values/app.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { Form } from 'formsy-react';
4 |
5 | import MyInput from './../components/Input';
6 | import MySelect from './../components/Select';
7 |
8 | const user = {
9 | name: 'Sam',
10 | free: true,
11 | hair: 'brown'
12 | };
13 |
14 | const App = React.createClass({
15 | submit(data) {
16 | alert(JSON.stringify(data, null, 4));
17 | },
18 | resetForm() {
19 | this.refs.form.reset();
20 | },
21 | render() {
22 | return (
23 |
24 |
25 |
26 |
34 |
35 |
36 | Reset
37 | Submit
38 |
39 |
40 | );
41 | }
42 | });
43 |
44 | ReactDOM.render( , document.getElementById('example'));
45 |
--------------------------------------------------------------------------------
/examples/reset-values/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Reset Values
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/webpack.config.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var path = require('path');
3 | var webpack = require('webpack');
4 |
5 | function isDirectory(dir) {
6 | return fs.lstatSync(dir).isDirectory();
7 | }
8 |
9 | module.exports = {
10 |
11 | devtool: 'inline-source-map',
12 |
13 | entry: fs.readdirSync(__dirname).reduce(function (entries, dir) {
14 | var isDraft = dir.charAt(0) === '_' || dir.indexOf('components') >= 0;
15 |
16 | if (!isDraft && isDirectory(path.join(__dirname, dir))) {
17 | entries[dir] = path.join(__dirname, dir, 'app.js');
18 | }
19 |
20 | return entries;
21 | }, {}),
22 |
23 | output: {
24 | path: 'examples/__build__',
25 | filename: '[name].js',
26 | chunkFilename: '[id].chunk.js',
27 | publicPath: '/__build__/'
28 | },
29 |
30 | module: {
31 | loaders: [
32 | { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }
33 | ]
34 | },
35 |
36 | resolve: {
37 | alias: {
38 | 'formsy-react': '../../src/main'
39 | }
40 | },
41 |
42 | plugins: [
43 | new webpack.optimize.CommonsChunkPlugin('shared.js'),
44 | new webpack.DefinePlugin({
45 | 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
46 | })
47 | ]
48 |
49 | };
50 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "formsy-react",
3 | "version": "0.19.5",
4 | "description": "A form input builder and validator for React JS",
5 | "repository": {
6 | "type": "git",
7 | "url": "https://github.com/christianalfoni/formsy-react.git"
8 | },
9 | "main": "lib/main.js",
10 | "scripts": {
11 | "build": "NODE_ENV=production webpack -p --config webpack.production.config.js",
12 | "test": "babel-node testrunner",
13 | "examples": "webpack-dev-server --config examples/webpack.config.js --content-base examples",
14 | "prepublish": "babel ./src/ -d ./lib/"
15 | },
16 | "author": "Christian Alfoni",
17 | "license": "MIT",
18 | "keywords": [
19 | "react",
20 | "form",
21 | "forms",
22 | "validation",
23 | "react-component"
24 | ],
25 | "dependencies": {
26 | "form-data-to-object": "^0.2.0"
27 | },
28 | "devDependencies": {
29 | "babel-cli": "^6.6.5",
30 | "babel-loader": "^6.2.4",
31 | "babel-preset-es2015": "^6.6.0",
32 | "babel-preset-react": "^6.5.0",
33 | "babel-preset-stage-2": "^6.5.0",
34 | "create-react-class": "^15.6.0",
35 | "jsdom": "^6.5.1",
36 | "nodeunit": "^0.9.1",
37 | "prop-types": "^15.5.10",
38 | "react": "^15.0.0",
39 | "react-addons-pure-render-mixin": "^15.0.0",
40 | "react-addons-test-utils": "^15.0.0",
41 | "react-dom": "^15.0.0",
42 | "sinon": "^1.17.3",
43 | "webpack": "^1.12.14",
44 | "webpack-dev-server": "^1.14.1"
45 | },
46 | "peerDependencies": {
47 | "react": "^0.14.0 || ^15.0.0"
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/Decorator.js:
--------------------------------------------------------------------------------
1 | var React = global.React || require('react');
2 | var createReactClass = require('create-react-class');
3 | var Mixin = require('./Mixin.js');
4 | module.exports = function () {
5 | return function (Component) {
6 | return createReactClass({
7 | mixins: [Mixin],
8 | render: function () {
9 | return React.createElement(Component, {
10 | setValidations: this.setValidations,
11 | setValue: this.setValue,
12 | resetValue: this.resetValue,
13 | getValue: this.getValue,
14 | hasValue: this.hasValue,
15 | getErrorMessage: this.getErrorMessage,
16 | getErrorMessages: this.getErrorMessages,
17 | isFormDisabled: this.isFormDisabled,
18 | isValid: this.isValid,
19 | isPristine: this.isPristine,
20 | isFormSubmitted: this.isFormSubmitted,
21 | isRequired: this.isRequired,
22 | showRequired: this.showRequired,
23 | showError: this.showError,
24 | isValidValue: this.isValidValue,
25 | ...this.props
26 | });
27 | }
28 | });
29 | };
30 | };
31 |
--------------------------------------------------------------------------------
/src/HOC.js:
--------------------------------------------------------------------------------
1 | var React = global.React || require('react');
2 | var createReactClass = require('create-react-class');
3 | var Mixin = require('./Mixin.js');
4 | module.exports = function (Component) {
5 | return createReactClass({
6 | displayName: 'Formsy(' + getDisplayName(Component) + ')',
7 | mixins: [Mixin],
8 |
9 | render: function () {
10 | const { innerRef } = this.props;
11 | const propsForElement = {
12 | setValidations: this.setValidations,
13 | setValue: this.setValue,
14 | resetValue: this.resetValue,
15 | getValue: this.getValue,
16 | hasValue: this.hasValue,
17 | getErrorMessage: this.getErrorMessage,
18 | getErrorMessages: this.getErrorMessages,
19 | isFormDisabled: this.isFormDisabled,
20 | isValid: this.isValid,
21 | isPristine: this.isPristine,
22 | isFormSubmitted: this.isFormSubmitted,
23 | isRequired: this.isRequired,
24 | showRequired: this.showRequired,
25 | showError: this.showError,
26 | isValidValue: this.isValidValue,
27 | ...this.props
28 | };
29 |
30 | if (innerRef) {
31 | propsForElement.ref = innerRef;
32 | }
33 | return React.createElement(Component, propsForElement);
34 | }
35 | });
36 | };
37 |
38 | function getDisplayName(Component) {
39 | return (
40 | Component.displayName ||
41 | Component.name ||
42 | (typeof Component === 'string' ? Component : 'Component')
43 | );
44 | }
45 |
--------------------------------------------------------------------------------
/src/Mixin.js:
--------------------------------------------------------------------------------
1 | var PropTypes = require('prop-types');
2 | var utils = require('./utils.js');
3 | var React = global.React || require('react');
4 |
5 | var convertValidationsToObject = function (validations) {
6 |
7 | if (typeof validations === 'string') {
8 |
9 | return validations.split(/\,(?![^{\[]*[}\]])/g).reduce(function (validations, validation) {
10 | var args = validation.split(':');
11 | var validateMethod = args.shift();
12 |
13 | args = args.map(function (arg) {
14 | try {
15 | return JSON.parse(arg);
16 | } catch (e) {
17 | return arg; // It is a string if it can not parse it
18 | }
19 | });
20 |
21 | if (args.length > 1) {
22 | throw new Error('Formsy does not support multiple args on string validations. Use object format of validations instead.');
23 | }
24 |
25 | validations[validateMethod] = args.length ? args[0] : true;
26 | return validations;
27 | }, {});
28 |
29 | }
30 |
31 | return validations || {};
32 | };
33 |
34 | module.exports = {
35 | getInitialState: function () {
36 | return {
37 | _value: this.props.value,
38 | _isRequired: false,
39 | _isValid: true,
40 | _isPristine: true,
41 | _pristineValue: this.props.value,
42 | _validationError: [],
43 | _externalError: null,
44 | _formSubmitted: false
45 | };
46 | },
47 | contextTypes: {
48 | formsy: PropTypes.object // What about required?
49 | },
50 | getDefaultProps: function () {
51 | return {
52 | validationError: '',
53 | validationErrors: {}
54 | };
55 | },
56 |
57 | componentWillMount: function () {
58 | var configure = function () {
59 | this.setValidations(this.props.validations, this.props.required);
60 |
61 | // Pass a function instead?
62 | this.context.formsy.attachToForm(this);
63 | //this.props._attachToForm(this);
64 | }.bind(this);
65 |
66 | if (!this.props.name) {
67 | throw new Error('Form Input requires a name property when used');
68 | }
69 |
70 | /*
71 | if (!this.props._attachToForm) {
72 | return setTimeout(function () {
73 | if (!this.isMounted()) return;
74 | if (!this.props._attachToForm) {
75 | throw new Error('Form Mixin requires component to be nested in a Form');
76 | }
77 | configure();
78 | }.bind(this), 0);
79 | }
80 | */
81 | configure();
82 | },
83 |
84 | // We have to make the validate method is kept when new props are added
85 | componentWillReceiveProps: function (nextProps) {
86 | this.setValidations(nextProps.validations, nextProps.required);
87 |
88 | },
89 |
90 | componentDidUpdate: function (prevProps) {
91 |
92 | // If the value passed has changed, set it. If value is not passed it will
93 | // internally update, and this will never run
94 | if (!utils.isSame(this.props.value, prevProps.value)) {
95 | this.setValue(this.props.value);
96 | }
97 |
98 | // If validations or required is changed, run a new validation
99 | if (!utils.isSame(this.props.validations, prevProps.validations) || !utils.isSame(this.props.required, prevProps.required)) {
100 | this.context.formsy.validate(this);
101 | }
102 | },
103 |
104 | // Detach it when component unmounts
105 | componentWillUnmount: function () {
106 | this.context.formsy.detachFromForm(this);
107 | //this.props._detachFromForm(this);
108 | },
109 |
110 | setValidations: function (validations, required) {
111 |
112 | // Add validations to the store itself as the props object can not be modified
113 | this._validations = convertValidationsToObject(validations) || {};
114 | this._requiredValidations = required === true ? {isDefaultRequiredValue: true} : convertValidationsToObject(required);
115 |
116 | },
117 |
118 | // We validate after the value has been set
119 | setValue: function (value) {
120 | this.setState({
121 | _value: value,
122 | _isPristine: false
123 | }, function () {
124 | this.context.formsy.validate(this);
125 | //this.props._validate(this);
126 | }.bind(this));
127 | },
128 | resetValue: function () {
129 | this.setState({
130 | _value: this.state._pristineValue,
131 | _isPristine: true
132 | }, function () {
133 | this.context.formsy.validate(this);
134 | //this.props._validate(this);
135 | });
136 | },
137 | getValue: function () {
138 | return this.state._value;
139 | },
140 | hasValue: function () {
141 | return this.state._value !== '';
142 | },
143 | getErrorMessage: function () {
144 | var messages = this.getErrorMessages();
145 | return messages.length ? messages[0] : null;
146 | },
147 | getErrorMessages: function () {
148 | return !this.isValid() || this.showRequired() ? (this.state._externalError || this.state._validationError || []) : [];
149 | },
150 | isFormDisabled: function () {
151 | return this.context.formsy.isFormDisabled();
152 | //return this.props._isFormDisabled();
153 | },
154 | isValid: function () {
155 | return this.state._isValid;
156 | },
157 | isPristine: function () {
158 | return this.state._isPristine;
159 | },
160 | isFormSubmitted: function () {
161 | return this.state._formSubmitted;
162 | },
163 | isRequired: function () {
164 | return !!this.props.required;
165 | },
166 | showRequired: function () {
167 | return this.state._isRequired;
168 | },
169 | showError: function () {
170 | return !this.showRequired() && !this.isValid();
171 | },
172 | isValidValue: function (value) {
173 | return this.context.formsy.isValidValue.call(null, this, value);
174 | //return this.props._isValidValue.call(null, this, value);
175 | }
176 | };
177 |
--------------------------------------------------------------------------------
/src/main.js:
--------------------------------------------------------------------------------
1 | var PropTypes = require('prop-types');
2 | var React = global.React || require('react');
3 | var createReactClass = require('create-react-class');
4 | var Formsy = {};
5 | var validationRules = require('./validationRules.js');
6 | var formDataToObject = require('form-data-to-object');
7 | var utils = require('./utils.js');
8 | var Mixin = require('./Mixin.js');
9 | var HOC = require('./HOC.js');
10 | var Decorator = require('./Decorator.js');
11 | var options = {};
12 | var emptyArray = [];
13 |
14 | Formsy.Mixin = Mixin;
15 | Formsy.HOC = HOC;
16 | Formsy.Decorator = Decorator;
17 |
18 | Formsy.defaults = function (passedOptions) {
19 | options = passedOptions;
20 | };
21 |
22 | Formsy.addValidationRule = function (name, func) {
23 | validationRules[name] = func;
24 | };
25 |
26 | Formsy.Form = createReactClass({
27 | displayName: 'Formsy',
28 | getInitialState: function () {
29 | return {
30 | isValid: true,
31 | isSubmitting: false,
32 | canChange: false
33 | };
34 | },
35 | getDefaultProps: function () {
36 | return {
37 | onSuccess: function () {},
38 | onError: function () {},
39 | onSubmit: function () {},
40 | onValidSubmit: function () {},
41 | onInvalidSubmit: function () {},
42 | onValid: function () {},
43 | onInvalid: function () {},
44 | onChange: function () {},
45 | validationErrors: null,
46 | preventExternalInvalidation: false
47 | };
48 | },
49 |
50 | childContextTypes: {
51 | formsy: PropTypes.object
52 | },
53 | getChildContext: function () {
54 | return {
55 | formsy: {
56 | attachToForm: this.attachToForm,
57 | detachFromForm: this.detachFromForm,
58 | validate: this.validate,
59 | isFormDisabled: this.isFormDisabled,
60 | isValidValue: (component, value) => {
61 | return this.runValidation(component, value).isValid;
62 | }
63 | }
64 | }
65 | },
66 |
67 | // Add a map to store the inputs of the form, a model to store
68 | // the values of the form and register child inputs
69 | componentWillMount: function () {
70 | this.inputs = [];
71 | },
72 |
73 | componentDidMount: function () {
74 | this.validateForm();
75 | },
76 |
77 | componentWillUpdate: function () {
78 | // Keep a reference to input names before form updates,
79 | // to check if inputs has changed after render
80 | this.prevInputNames = this.inputs.map(component => component.props.name);
81 | },
82 |
83 | componentDidUpdate: function () {
84 |
85 | if (this.props.validationErrors && typeof this.props.validationErrors === 'object' && Object.keys(this.props.validationErrors).length > 0) {
86 | this.setInputValidationErrors(this.props.validationErrors);
87 | }
88 |
89 | var newInputNames = this.inputs.map(component => component.props.name);
90 | if (utils.arraysDiffer(this.prevInputNames, newInputNames)) {
91 | this.validateForm();
92 | }
93 |
94 | },
95 |
96 | // Allow resetting to specified data
97 | reset: function (data) {
98 | this.setFormPristine(true);
99 | this.resetModel(data);
100 | },
101 |
102 | // Update model, submit to url prop and send the model
103 | submit: function (event) {
104 |
105 | event && event.preventDefault();
106 |
107 | // Trigger form as not pristine.
108 | // If any inputs have not been touched yet this will make them dirty
109 | // so validation becomes visible (if based on isPristine)
110 | this.setFormPristine(false);
111 | var model = this.getModel();
112 | this.props.onSubmit(model, this.resetModel, this.updateInputsWithError);
113 | this.state.isValid ? this.props.onValidSubmit(model, this.resetModel, this.updateInputsWithError) : this.props.onInvalidSubmit(model, this.resetModel, this.updateInputsWithError);
114 |
115 | },
116 |
117 | mapModel: function (model) {
118 |
119 | if (this.props.mapping) {
120 | return this.props.mapping(model)
121 | } else {
122 | return formDataToObject.toObj(Object.keys(model).reduce((mappedModel, key) => {
123 |
124 | var keyArray = key.split('.');
125 | var base = mappedModel;
126 | while (keyArray.length) {
127 | var currentKey = keyArray.shift();
128 | base = (base[currentKey] = keyArray.length ? base[currentKey] || {} : model[key]);
129 | }
130 |
131 | return mappedModel;
132 |
133 | }, {}));
134 | }
135 | },
136 |
137 | getModel: function () {
138 | var currentValues = this.getCurrentValues();
139 | return this.mapModel(currentValues);
140 | },
141 |
142 | // Reset each key in the model to the original / initial / specified value
143 | resetModel: function (data) {
144 | this.inputs.forEach(component => {
145 | var name = component.props.name;
146 | if (data && data.hasOwnProperty(name)) {
147 | component.setValue(data[name]);
148 | } else {
149 | component.resetValue();
150 | }
151 | });
152 | this.validateForm();
153 | },
154 |
155 | setInputValidationErrors: function (errors) {
156 | this.inputs.forEach(component => {
157 | var name = component.props.name;
158 | var args = [{
159 | _isValid: !(name in errors),
160 | _validationError: typeof errors[name] === 'string' ? [errors[name]] : errors[name]
161 | }];
162 | component.setState.apply(component, args);
163 | });
164 | },
165 |
166 | // Checks if the values have changed from their initial value
167 | isChanged: function() {
168 | return !utils.isSame(this.getPristineValues(), this.getCurrentValues());
169 | },
170 |
171 | getPristineValues: function() {
172 | return this.inputs.reduce((data, component) => {
173 | var name = component.props.name;
174 | data[name] = component.props.value;
175 | return data;
176 | }, {});
177 | },
178 |
179 | // Go through errors from server and grab the components
180 | // stored in the inputs map. Change their state to invalid
181 | // and set the serverError message
182 | updateInputsWithError: function (errors) {
183 | Object.keys(errors).forEach((name, index) => {
184 | var component = utils.find(this.inputs, component => component.props.name === name);
185 | if (!component) {
186 | throw new Error('You are trying to update an input that does not exist. ' +
187 | 'Verify errors object with input names. ' + JSON.stringify(errors));
188 | }
189 | var args = [{
190 | _isValid: this.props.preventExternalInvalidation || false,
191 | _externalError: typeof errors[name] === 'string' ? [errors[name]] : errors[name]
192 | }];
193 | component.setState.apply(component, args);
194 | });
195 | },
196 |
197 | isFormDisabled: function () {
198 | return this.props.disabled;
199 | },
200 |
201 | getCurrentValues: function () {
202 | return this.inputs.reduce((data, component) => {
203 | var name = component.props.name;
204 | data[name] = component.state._value;
205 | return data;
206 | }, {});
207 | },
208 |
209 | setFormPristine: function (isPristine) {
210 | this.setState({
211 | _formSubmitted: !isPristine
212 | });
213 |
214 | // Iterate through each component and set it as pristine
215 | // or "dirty".
216 | this.inputs.forEach((component, index) => {
217 | component.setState({
218 | _formSubmitted: !isPristine,
219 | _isPristine: isPristine
220 | });
221 | });
222 | },
223 |
224 | // Use the binded values and the actual input value to
225 | // validate the input and set its state. Then check the
226 | // state of the form itself
227 | validate: function (component) {
228 |
229 | // Trigger onChange
230 | if (this.state.canChange) {
231 | this.props.onChange(this.getCurrentValues(), this.isChanged());
232 | }
233 |
234 | var validation = this.runValidation(component);
235 | // Run through the validations, split them up and call
236 | // the validator IF there is a value or it is required
237 | component.setState({
238 | _isValid: validation.isValid,
239 | _isRequired: validation.isRequired,
240 | _validationError: validation.error,
241 | _externalError: null
242 | }, this.validateForm);
243 |
244 | },
245 |
246 | // Checks validation on current value or a passed value
247 | runValidation: function (component, value) {
248 |
249 | var currentValues = this.getCurrentValues();
250 | var validationErrors = component.props.validationErrors;
251 | var validationError = component.props.validationError;
252 | value = arguments.length === 2 ? value : component.state._value;
253 |
254 | var validationResults = this.runRules(value, currentValues, component._validations);
255 | var requiredResults = this.runRules(value, currentValues, component._requiredValidations);
256 |
257 | // the component defines an explicit validate function
258 | if (typeof component.validate === "function") {
259 | validationResults.failed = component.validate() ? [] : ['failed'];
260 | }
261 |
262 | var isRequired = Object.keys(component._requiredValidations).length ? !!requiredResults.success.length : false;
263 | var isValid = !validationResults.failed.length && !(this.props.validationErrors && this.props.validationErrors[component.props.name]);
264 |
265 | return {
266 | isRequired: isRequired,
267 | isValid: isRequired ? false : isValid,
268 | error: (function () {
269 |
270 | if (isValid && !isRequired) {
271 | return emptyArray;
272 | }
273 |
274 | if (validationResults.errors.length) {
275 | return validationResults.errors;
276 | }
277 |
278 | if (this.props.validationErrors && this.props.validationErrors[component.props.name]) {
279 | return typeof this.props.validationErrors[component.props.name] === 'string' ? [this.props.validationErrors[component.props.name]] : this.props.validationErrors[component.props.name];
280 | }
281 |
282 | if (isRequired) {
283 | var error = validationErrors[requiredResults.success[0]];
284 | return error ? [error] : null;
285 | }
286 |
287 | if (validationResults.failed.length) {
288 | return validationResults.failed.map(function(failed) {
289 | return validationErrors[failed] ? validationErrors[failed] : validationError;
290 | }).filter(function(x, pos, arr) {
291 | // Remove duplicates
292 | return arr.indexOf(x) === pos;
293 | });
294 | }
295 |
296 | }.call(this))
297 | };
298 |
299 | },
300 |
301 | runRules: function (value, currentValues, validations) {
302 |
303 | var results = {
304 | errors: [],
305 | failed: [],
306 | success: []
307 | };
308 | if (Object.keys(validations).length) {
309 | Object.keys(validations).forEach(function (validationMethod) {
310 |
311 | if (validationRules[validationMethod] && typeof validations[validationMethod] === 'function') {
312 | throw new Error('Formsy does not allow you to override default validations: ' + validationMethod);
313 | }
314 |
315 | if (!validationRules[validationMethod] && typeof validations[validationMethod] !== 'function') {
316 | throw new Error('Formsy does not have the validation rule: ' + validationMethod);
317 | }
318 |
319 | if (typeof validations[validationMethod] === 'function') {
320 | var validation = validations[validationMethod](currentValues, value);
321 | if (typeof validation === 'string') {
322 | results.errors.push(validation);
323 | results.failed.push(validationMethod);
324 | } else if (!validation) {
325 | results.failed.push(validationMethod);
326 | }
327 | return;
328 |
329 | } else if (typeof validations[validationMethod] !== 'function') {
330 | var validation = validationRules[validationMethod](currentValues, value, validations[validationMethod]);
331 | if (typeof validation === 'string') {
332 | results.errors.push(validation);
333 | results.failed.push(validationMethod);
334 | } else if (!validation) {
335 | results.failed.push(validationMethod);
336 | } else {
337 | results.success.push(validationMethod);
338 | }
339 | return;
340 |
341 | }
342 |
343 | return results.success.push(validationMethod);
344 |
345 | });
346 | }
347 |
348 | return results;
349 |
350 | },
351 |
352 | // Validate the form by going through all child input components
353 | // and check their state
354 | validateForm: function () {
355 |
356 | // We need a callback as we are validating all inputs again. This will
357 | // run when the last component has set its state
358 | var onValidationComplete = function () {
359 | var allIsValid = this.inputs.every(component => {
360 | return component.state._isValid;
361 | });
362 |
363 | this.setState({
364 | isValid: allIsValid
365 | });
366 |
367 | if (allIsValid) {
368 | this.props.onValid();
369 | } else {
370 | this.props.onInvalid();
371 | }
372 |
373 | // Tell the form that it can start to trigger change events
374 | this.setState({
375 | canChange: true
376 | });
377 |
378 | }.bind(this);
379 |
380 | // Run validation again in case affected by other inputs. The
381 | // last component validated will run the onValidationComplete callback
382 | this.inputs.forEach((component, index) => {
383 | var validation = this.runValidation(component);
384 | if (validation.isValid && component.state._externalError) {
385 | validation.isValid = false;
386 | }
387 | component.setState({
388 | _isValid: validation.isValid,
389 | _isRequired: validation.isRequired,
390 | _validationError: validation.error,
391 | _externalError: !validation.isValid && component.state._externalError ? component.state._externalError : null
392 | }, index === this.inputs.length - 1 ? onValidationComplete : null);
393 | });
394 |
395 | // If there are no inputs, set state where form is ready to trigger
396 | // change event. New inputs might be added later
397 | if (!this.inputs.length) {
398 | this.setState({
399 | canChange: true
400 | });
401 | }
402 | },
403 |
404 | // Method put on each input component to register
405 | // itself to the form
406 | attachToForm: function (component) {
407 |
408 | if (this.inputs.indexOf(component) === -1) {
409 | this.inputs.push(component);
410 | }
411 |
412 | this.validate(component);
413 | },
414 |
415 | // Method put on each input component to unregister
416 | // itself from the form
417 | detachFromForm: function (component) {
418 | var componentPos = this.inputs.indexOf(component);
419 |
420 | if (componentPos !== -1) {
421 | this.inputs = this.inputs.slice(0, componentPos)
422 | .concat(this.inputs.slice(componentPos + 1));
423 | }
424 |
425 | this.validateForm();
426 | },
427 | render: function () {
428 | var {
429 | mapping,
430 | validationErrors,
431 | onSubmit,
432 | onValid,
433 | onValidSubmit,
434 | onInvalid,
435 | onInvalidSubmit,
436 | onChange,
437 | reset,
438 | preventExternalInvalidation,
439 | onSuccess,
440 | onError,
441 | ...nonFormsyProps
442 | } = this.props;
443 |
444 | return (
445 |
448 | );
449 |
450 | }
451 | });
452 |
453 | if (!global.exports && !global.module && (!global.define || !global.define.amd)) {
454 | global.Formsy = Formsy;
455 | }
456 |
457 | module.exports = Formsy;
458 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | arraysDiffer: function (a, b) {
3 | var isDifferent = false;
4 | if (a.length !== b.length) {
5 | isDifferent = true;
6 | } else {
7 | a.forEach(function (item, index) {
8 | if (!this.isSame(item, b[index])) {
9 | isDifferent = true;
10 | }
11 | }, this);
12 | }
13 | return isDifferent;
14 | },
15 |
16 | objectsDiffer: function (a, b) {
17 | var isDifferent = false;
18 | if (Object.keys(a).length !== Object.keys(b).length) {
19 | isDifferent = true;
20 | } else {
21 | Object.keys(a).forEach(function (key) {
22 | if (!this.isSame(a[key], b[key])) {
23 | isDifferent = true;
24 | }
25 | }, this);
26 | }
27 | return isDifferent;
28 | },
29 |
30 | isSame: function (a, b) {
31 | if (typeof a !== typeof b) {
32 | return false;
33 | } else if (Array.isArray(a) && Array.isArray(b)) {
34 | return !this.arraysDiffer(a, b);
35 | } else if (typeof a === 'function') {
36 | return a.toString() === b.toString();
37 | } else if (typeof a === 'object' && a !== null && b !== null) {
38 | return !this.objectsDiffer(a, b);
39 | }
40 |
41 | return a === b;
42 | },
43 |
44 | find: function (collection, fn) {
45 | for (var i = 0, l = collection.length; i < l; i++) {
46 | var item = collection[i];
47 | if (fn(item)) {
48 | return item;
49 | }
50 | }
51 | return null;
52 | }
53 | };
54 |
--------------------------------------------------------------------------------
/src/validationRules.js:
--------------------------------------------------------------------------------
1 | var isExisty = function (value) {
2 | return value !== null && value !== undefined;
3 | };
4 |
5 | var isEmpty = function (value) {
6 | return value === '';
7 | };
8 |
9 | var validations = {
10 | isDefaultRequiredValue: function (values, value) {
11 | return value === undefined || value === '';
12 | },
13 | isExisty: function (values, value) {
14 | return isExisty(value);
15 | },
16 | matchRegexp: function (values, value, regexp) {
17 | return !isExisty(value) || isEmpty(value) || regexp.test(value);
18 | },
19 | isUndefined: function (values, value) {
20 | return value === undefined;
21 | },
22 | isEmptyString: function (values, value) {
23 | return isEmpty(value);
24 | },
25 | isEmail: function (values, value) {
26 | return validations.matchRegexp(values, value, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i);
27 | },
28 | isUrl: function (values, value) {
29 | return validations.matchRegexp(values, value, /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i);
30 | },
31 | isTrue: function (values, value) {
32 | return value === true;
33 | },
34 | isFalse: function (values, value) {
35 | return value === false;
36 | },
37 | isNumeric: function (values, value) {
38 | if (typeof value === 'number') {
39 | return true;
40 | }
41 | return validations.matchRegexp(values, value, /^[-+]?(?:\d*[.])?\d+$/);
42 | },
43 | isAlpha: function (values, value) {
44 | return validations.matchRegexp(values, value, /^[A-Z]+$/i);
45 | },
46 | isAlphanumeric: function (values, value) {
47 | return validations.matchRegexp(values, value, /^[0-9A-Z]+$/i);
48 | },
49 | isInt: function (values, value) {
50 | return validations.matchRegexp(values, value, /^(?:[-+]?(?:0|[1-9]\d*))$/);
51 | },
52 | isFloat: function (values, value) {
53 | return validations.matchRegexp(values, value, /^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][\+\-]?(?:\d+))?$/);
54 | },
55 | isWords: function (values, value) {
56 | return validations.matchRegexp(values, value, /^[A-Z\s]+$/i);
57 | },
58 | isSpecialWords: function (values, value) {
59 | return validations.matchRegexp(values, value, /^[A-Z\s\u00C0-\u017F]+$/i);
60 | },
61 | isLength: function (values, value, length) {
62 | return !isExisty(value) || isEmpty(value) || value.length === length;
63 | },
64 | equals: function (values, value, eql) {
65 | return !isExisty(value) || isEmpty(value) || value == eql;
66 | },
67 | equalsField: function (values, value, field) {
68 | return value == values[field];
69 | },
70 | maxLength: function (values, value, length) {
71 | return !isExisty(value) || value.length <= length;
72 | },
73 | minLength: function (values, value, length) {
74 | return !isExisty(value) || isEmpty(value) || value.length >= length;
75 | }
76 | };
77 |
78 | module.exports = validations;
79 |
--------------------------------------------------------------------------------
/testrunner.js:
--------------------------------------------------------------------------------
1 | import path from 'path';
2 | import testrunner from 'nodeunit/lib/reporters/default.js';
3 | import {jsdom} from 'jsdom';
4 |
5 | global.document = jsdom();
6 | global.window = document.defaultView;
7 | global.navigator = global.window.navigator;
8 |
9 | testrunner.run(['tests'], {
10 | "error_prefix": "\u001B[31m",
11 | "error_suffix": "\u001B[39m",
12 | "ok_prefix": "\u001B[32m",
13 | "ok_suffix": "\u001B[39m",
14 | "bold_prefix": "\u001B[1m",
15 | "bold_suffix": "\u001B[22m",
16 | "assertion_prefix": "\u001B[35m",
17 | "assertion_suffix": "\u001B[39m"
18 | }, function(err) {
19 | if (err) {
20 | process.exit(1);
21 | }
22 | });
23 |
--------------------------------------------------------------------------------
/tests/Element-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 | import PureRenderMixin from 'react-addons-pure-render-mixin';
4 | import sinon from 'sinon';
5 |
6 | import Formsy from './..';
7 | import TestInput, { InputFactory } from './utils/TestInput';
8 | import immediate from './utils/immediate';
9 |
10 | export default {
11 |
12 | 'should return passed and setValue() value when using getValue()': function (test) {
13 |
14 | const form = TestUtils.renderIntoDocument(
15 |
16 |
17 |
18 | );
19 |
20 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
21 | test.equal(input.value, 'foo');
22 | TestUtils.Simulate.change(input, {target: {value: 'foobar'}});
23 | test.equal(input.value, 'foobar');
24 |
25 | test.done();
26 |
27 | },
28 |
29 | 'should set back to pristine value when running reset': function (test) {
30 |
31 | let reset = null;
32 | const Input = InputFactory({
33 | componentDidMount() {
34 | reset = this.resetValue;
35 | }
36 | });
37 | const form = TestUtils.renderIntoDocument(
38 |
39 |
40 |
41 | );
42 |
43 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
44 | TestUtils.Simulate.change(input, {target: {value: 'foobar'}});
45 | reset();
46 | test.equal(input.value, 'foo');
47 |
48 | test.done();
49 |
50 | },
51 |
52 | 'should return error message passed when calling getErrorMessage()': function (test) {
53 |
54 | let getErrorMessage = null;
55 | const Input = InputFactory({
56 | componentDidMount() {
57 | getErrorMessage = this.getErrorMessage;
58 | }
59 | });
60 | TestUtils.renderIntoDocument(
61 |
62 |
63 |
64 | );
65 |
66 | test.equal(getErrorMessage(), 'Has to be email');
67 |
68 | test.done();
69 |
70 | },
71 |
72 | 'should return true or false when calling isValid() depending on valid state': function (test) {
73 |
74 | let isValid = null;
75 | const Input = InputFactory({
76 | componentDidMount() {
77 | isValid = this.isValid;
78 | }
79 | });
80 | const form = TestUtils.renderIntoDocument(
81 |
82 |
83 |
84 | );
85 |
86 | test.equal(isValid(), false);
87 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
88 | TestUtils.Simulate.change(input, {target: {value: 'foo@foo.com'}});
89 | test.equal(isValid(), true);
90 |
91 | test.done();
92 |
93 | },
94 |
95 | 'should return true or false when calling isRequired() depending on passed required attribute': function (test) {
96 |
97 | const isRequireds = [];
98 | const Input = InputFactory({
99 | componentDidMount() {
100 | isRequireds.push(this.isRequired);
101 | }
102 | });
103 | TestUtils.renderIntoDocument(
104 |
105 |
106 |
107 |
108 |
109 | );
110 |
111 | test.equal(isRequireds[0](), false);
112 | test.equal(isRequireds[1](), true);
113 | test.equal(isRequireds[2](), true);
114 |
115 | test.done();
116 |
117 | },
118 |
119 | 'should return true or false when calling showRequired() depending on input being empty and required is passed, or not': function (test) {
120 |
121 | const showRequireds = [];
122 | const Input = InputFactory({
123 | componentDidMount() {
124 | showRequireds.push(this.showRequired);
125 | }
126 | });
127 | TestUtils.renderIntoDocument(
128 |
129 |
130 |
131 |
132 |
133 | );
134 |
135 | test.equal(showRequireds[0](), false);
136 | test.equal(showRequireds[1](), true);
137 | test.equal(showRequireds[2](), false);
138 |
139 | test.done();
140 |
141 | },
142 |
143 | 'should return true or false when calling isPristine() depending on input has been "touched" or not': function (test) {
144 |
145 | let isPristine = null;
146 | const Input = InputFactory({
147 | componentDidMount() {
148 | isPristine = this.isPristine;
149 | }
150 | });
151 | const form = TestUtils.renderIntoDocument(
152 |
153 |
154 |
155 | );
156 |
157 | test.equal(isPristine(), true);
158 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
159 | TestUtils.Simulate.change(input, {target: {value: 'foo'}});
160 | test.equal(isPristine(), false);
161 |
162 | test.done();
163 |
164 | },
165 |
166 | 'should allow an undefined value to be updated to a value': function (test) {
167 |
168 | const TestForm = React.createClass({
169 | getInitialState() {
170 | return {value: undefined};
171 | },
172 | changeValue() {
173 | this.setState({
174 | value: 'foo'
175 | });
176 | },
177 | render() {
178 | return (
179 |
180 |
181 |
182 | );
183 | }
184 | });
185 | const form = TestUtils.renderIntoDocument( );
186 |
187 | form.changeValue();
188 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
189 | immediate(() => {
190 | test.equal(input.value, 'foo');
191 | test.done();
192 | });
193 |
194 | },
195 |
196 | 'should be able to test a values validity': function (test) {
197 |
198 | const TestForm = React.createClass({
199 | render() {
200 | return (
201 |
202 |
203 |
204 | );
205 | }
206 | });
207 | const form = TestUtils.renderIntoDocument( );
208 |
209 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
210 | test.equal(input.isValidValue('foo@bar.com'), true);
211 | test.equal(input.isValidValue('foo@bar'), false);
212 | test.done();
213 |
214 | },
215 |
216 | 'should be able to use an object as validations property': function (test) {
217 |
218 | const TestForm = React.createClass({
219 | render() {
220 | return (
221 |
222 |
225 |
226 | );
227 | }
228 | });
229 | const form = TestUtils.renderIntoDocument( );
230 |
231 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
232 | test.equal(input.isValidValue('foo@bar.com'), true);
233 | test.equal(input.isValidValue('foo@bar'), false);
234 |
235 | test.done();
236 |
237 | },
238 |
239 | 'should be able to pass complex values to a validation rule': function (test) {
240 |
241 | const TestForm = React.createClass({
242 | render() {
243 | return (
244 |
245 |
248 |
249 | );
250 | }
251 | });
252 | const form = TestUtils.renderIntoDocument( );
253 |
254 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
255 | test.equal(inputComponent.isValid(), true);
256 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
257 | TestUtils.Simulate.change(input, {target: {value: 'bar'}});
258 | test.equal(inputComponent.isValid(), false);
259 |
260 | test.done();
261 |
262 | },
263 |
264 | 'should be able to run a function to validate': function (test) {
265 |
266 | const TestForm = React.createClass({
267 | customValidationA(values, value) {
268 | return value === 'foo';
269 | },
270 | customValidationB(values, value) {
271 | return value === 'foo' && values.A === 'foo';
272 | },
273 | render() {
274 | return (
275 |
276 |
279 |
282 |
283 | );
284 | }
285 | });
286 | const form = TestUtils.renderIntoDocument( );
287 |
288 | const inputComponent = TestUtils.scryRenderedComponentsWithType(form, TestInput);
289 | test.equal(inputComponent[0].isValid(), true);
290 | test.equal(inputComponent[1].isValid(), true);
291 | const input = TestUtils.scryRenderedDOMComponentsWithTag(form, 'INPUT');
292 | TestUtils.Simulate.change(input[0], {target: {value: 'bar'}});
293 | test.equal(inputComponent[0].isValid(), false);
294 | test.equal(inputComponent[1].isValid(), false);
295 |
296 | test.done();
297 |
298 | },
299 |
300 | 'should not override error messages with error messages passed by form if passed eror messages is an empty object': function (test) {
301 |
302 | const TestForm = React.createClass({
303 | render() {
304 | return (
305 |
306 |
309 |
310 | );
311 | }
312 | });
313 | const form = TestUtils.renderIntoDocument( );
314 |
315 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
316 | test.equal(inputComponent.getErrorMessage(), 'bar3');
317 |
318 | test.done();
319 |
320 | },
321 |
322 |
323 | 'should override all error messages with error messages passed by form': function (test) {
324 |
325 | const TestForm = React.createClass({
326 | render() {
327 | return (
328 |
329 |
332 |
333 | );
334 | }
335 | });
336 | const form = TestUtils.renderIntoDocument( );
337 |
338 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
339 | test.equal(inputComponent.getErrorMessage(), 'bar');
340 |
341 | test.done();
342 |
343 | },
344 |
345 | 'should override validation rules with required rules': function (test) {
346 |
347 | const TestForm = React.createClass({
348 | render() {
349 | return (
350 |
351 |
362 |
363 | );
364 | }
365 | });
366 | const form = TestUtils.renderIntoDocument( );
367 |
368 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
369 | test.equal(inputComponent.getErrorMessage(), 'bar3');
370 |
371 | test.done();
372 |
373 | },
374 |
375 | 'should fall back to default error message when non exist in validationErrors map': function (test) {
376 |
377 | const TestForm = React.createClass({
378 | render() {
379 | return (
380 |
381 |
389 |
390 | );
391 | }
392 | });
393 | const form = TestUtils.renderIntoDocument( );
394 |
395 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
396 | test.equal(inputComponent.getErrorMessage(), 'bar');
397 |
398 | test.done();
399 |
400 | },
401 |
402 | 'should not be valid if it is required and required rule is true': function (test) {
403 |
404 | const TestForm = React.createClass({
405 | render() {
406 | return (
407 |
408 |
411 |
412 | );
413 | }
414 | });
415 | const form = TestUtils.renderIntoDocument( );
416 |
417 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
418 | test.equal(inputComponent.isValid(), false);
419 |
420 | test.done();
421 |
422 | },
423 |
424 | 'should handle objects and arrays as values': function (test) {
425 |
426 | const TestForm = React.createClass({
427 | getInitialState() {
428 | return {
429 | foo: {foo: 'bar'},
430 | bar: ['foo']
431 | };
432 | },
433 | render() {
434 | return (
435 |
436 |
437 |
438 |
439 | );
440 | }
441 | });
442 | const form = TestUtils.renderIntoDocument( );
443 |
444 | form.setState({
445 | foo: {foo: 'foo'},
446 | bar: ['bar']
447 | });
448 |
449 | const inputs = TestUtils.scryRenderedComponentsWithType(form, TestInput);
450 | test.deepEqual(inputs[0].getValue(), {foo: 'foo'});
451 | test.deepEqual(inputs[1].getValue(), ['bar']);
452 |
453 | test.done();
454 |
455 | },
456 |
457 | 'should handle isFormDisabled with dynamic inputs': function (test) {
458 |
459 | const TestForm = React.createClass({
460 | getInitialState() {
461 | return {
462 | bool: true
463 | };
464 | },
465 | flip() {
466 | this.setState({
467 | bool: !this.state.bool
468 | });
469 | },
470 | render() {
471 | return (
472 |
473 | {this.state.bool ?
474 | :
475 |
476 | }
477 |
478 | );
479 | }
480 | });
481 | const form = TestUtils.renderIntoDocument( );
482 |
483 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
484 | test.equal(input.isFormDisabled(), true);
485 | form.flip();
486 | test.equal(input.isFormDisabled(), false);
487 |
488 | test.done();
489 |
490 | },
491 |
492 | 'should allow for dot notation in name which maps to a deep object': function (test) {
493 |
494 | const TestForm = React.createClass({
495 | onSubmit(model) {
496 | test.deepEqual(model, {foo: {bar: 'foo', test: 'test'}});
497 | },
498 | render() {
499 | return (
500 |
501 |
502 |
503 |
504 | );
505 | }
506 | });
507 | const form = TestUtils.renderIntoDocument( );
508 |
509 | test.expect(1);
510 |
511 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
512 | TestUtils.Simulate.submit(formEl);
513 |
514 | test.done();
515 |
516 | },
517 |
518 | 'should allow for application/x-www-form-urlencoded syntax and convert to object': function (test) {
519 |
520 | const TestForm = React.createClass({
521 | onSubmit(model) {
522 | test.deepEqual(model, {foo: ['foo', 'bar']});
523 | },
524 | render() {
525 | return (
526 |
527 |
528 |
529 |
530 | );
531 | }
532 | });
533 | const form = TestUtils.renderIntoDocument( );
534 |
535 | test.expect(1);
536 |
537 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
538 | TestUtils.Simulate.submit(formEl);
539 |
540 | test.done();
541 |
542 | },
543 |
544 | 'input should rendered once with PureRenderMixin': function (test) {
545 |
546 | var renderSpy = sinon.spy();
547 |
548 | const Input = InputFactory({
549 | mixins: [Formsy.Mixin, PureRenderMixin],
550 | render() {
551 | renderSpy();
552 | return ;
553 | }
554 | });
555 |
556 | const form = TestUtils.renderIntoDocument(
557 |
558 |
559 |
560 | );
561 |
562 | test.equal(renderSpy.calledOnce, true);
563 |
564 | test.done();
565 |
566 | }
567 |
568 | };
569 |
--------------------------------------------------------------------------------
/tests/Formsy-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import TestUtils from 'react-addons-test-utils';
4 |
5 | import Formsy from './..';
6 | import TestInput from './utils/TestInput';
7 | import TestInputHoc from './utils/TestInputHoc';
8 | import immediate from './utils/immediate';
9 | import sinon from 'sinon';
10 |
11 | export default {
12 |
13 | 'Setting up a form': {
14 | 'should expose the users DOM node through an innerRef prop': function (test) {
15 | const TestForm = React.createClass({
16 | render() {
17 | return (
18 |
19 | { this.name = c; }} />
20 |
21 | );
22 | }
23 | });
24 |
25 | const form = TestUtils.renderIntoDocument( );
26 | const input = form.name;
27 | test.equal(input.methodOnWrappedInstance('foo'), 'foo');
28 |
29 | test.done();
30 | },
31 |
32 | 'should render a form into the document': function (test) {
33 |
34 | const form = TestUtils.renderIntoDocument( );
35 | test.equal(ReactDOM.findDOMNode(form).tagName, 'FORM');
36 |
37 | test.done();
38 |
39 | },
40 |
41 | 'should set a class name if passed': function (test) {
42 |
43 | const form = TestUtils.renderIntoDocument( );
44 | test.equal(ReactDOM.findDOMNode(form).className, 'foo');
45 |
46 | test.done();
47 |
48 | },
49 |
50 | 'should allow for null/undefined children': function (test) {
51 |
52 | let model = null;
53 | const TestForm = React.createClass({
54 | render() {
55 | return (
56 | (model = formModel)}>
57 | Test
58 | { null }
59 | { undefined }
60 |
61 |
62 | );
63 | }
64 | });
65 |
66 | const form = TestUtils.renderIntoDocument( );
67 | immediate(() => {
68 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
69 | test.deepEqual(model, {name: 'foo'});
70 | test.done();
71 | });
72 |
73 | },
74 |
75 | 'should allow for inputs being added dynamically': function (test) {
76 |
77 | const inputs = [];
78 | let forceUpdate = null;
79 | let model = null;
80 | const TestForm = React.createClass({
81 | componentWillMount() {
82 | forceUpdate = this.forceUpdate.bind(this);
83 | },
84 | render() {
85 | return (
86 | (model = formModel)}>
87 | {inputs}
88 | );
89 | }
90 | });
91 | const form = TestUtils.renderIntoDocument( );
92 |
93 | // Wait before adding the input
94 | setTimeout(() => {
95 | inputs.push();
96 |
97 | forceUpdate(() => {
98 | // Wait for next event loop, as that does the form
99 | immediate(() => {
100 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
101 | test.ok('test' in model);
102 | test.done();
103 | });
104 |
105 | });
106 |
107 | }, 10);
108 |
109 | },
110 |
111 | 'should allow dynamically added inputs to update the form-model': function (test) {
112 |
113 | const inputs = [];
114 | let forceUpdate = null;
115 | let model = null;
116 | const TestForm = React.createClass({
117 | componentWillMount() {
118 | forceUpdate = this.forceUpdate.bind(this);
119 | },
120 | render() {
121 | return (
122 | (model = formModel)}>
123 | {inputs}
124 | );
125 | }
126 | });
127 | const form = TestUtils.renderIntoDocument( );
128 |
129 | // Wait before adding the input
130 | immediate(() => {
131 | inputs.push();
132 |
133 | forceUpdate(() => {
134 |
135 | // Wait for next event loop, as that does the form
136 | immediate(() => {
137 | TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'foo'}});
138 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
139 | test.equal(model.test, 'foo');
140 | test.done();
141 | });
142 |
143 | });
144 |
145 | });
146 |
147 | },
148 |
149 | 'should allow a dynamically updated input to update the form-model': function (test) {
150 |
151 | let forceUpdate = null;
152 | let model = null;
153 |
154 | const TestForm = React.createClass({
155 | componentWillMount() {
156 | forceUpdate = this.forceUpdate.bind(this);
157 | },
158 | render() {
159 | const input = ;
160 |
161 | return (
162 | (model = formModel)}>
163 | {input}
164 | );
165 | }
166 | });
167 | let form = TestUtils.renderIntoDocument( );
168 |
169 | // Wait before changing the input
170 | immediate(() => {
171 | form = TestUtils.renderIntoDocument( );
172 |
173 | forceUpdate(() => {
174 | // Wait for next event loop, as that does the form
175 | immediate(() => {
176 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
177 | test.equal(model.test, 'bar');
178 | test.done();
179 | });
180 |
181 | });
182 |
183 | });
184 |
185 | }
186 |
187 | },
188 |
189 | 'validations': {
190 |
191 | 'should run when the input changes': function (test) {
192 |
193 | const runRule = sinon.spy();
194 | const notRunRule = sinon.spy();
195 |
196 | Formsy.addValidationRule('runRule', runRule);
197 | Formsy.addValidationRule('notRunRule', notRunRule);
198 |
199 | const form = TestUtils.renderIntoDocument(
200 |
201 |
202 |
203 | );
204 |
205 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
206 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
207 | test.equal(runRule.calledWith({one: 'bar'}, 'bar', true), true);
208 | test.equal(notRunRule.called, false);
209 |
210 | test.done();
211 |
212 | },
213 |
214 | 'should allow the validation to be changed': function (test) {
215 |
216 | const ruleA = sinon.spy();
217 | const ruleB = sinon.spy();
218 | Formsy.addValidationRule('ruleA', ruleA);
219 | Formsy.addValidationRule('ruleB', ruleB);
220 |
221 | class TestForm extends React.Component {
222 | constructor(props) {
223 | super(props);
224 | this.state = {rule: 'ruleA'};
225 | }
226 | changeRule() {
227 | this.setState({
228 | rule: 'ruleB'
229 | });
230 | }
231 | render() {
232 | return (
233 |
234 |
235 |
236 | );
237 | }
238 | }
239 |
240 | const form = TestUtils.renderIntoDocument( );
241 | form.changeRule();
242 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
243 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
244 | test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true);
245 |
246 | test.done();
247 |
248 | },
249 |
250 | 'should invalidate a form if dynamically inserted input is invalid': function (test) {
251 |
252 | const isInValidSpy = sinon.spy();
253 |
254 | class TestForm extends React.Component {
255 | constructor(props) {
256 | super(props);
257 | this.state = {showSecondInput: false};
258 | }
259 | addInput() {
260 | this.setState({
261 | showSecondInput: true
262 | });
263 | }
264 | render() {
265 | return (
266 |
267 |
268 | {
269 | this.state.showSecondInput ?
270 |
271 | :
272 | null
273 | }
274 |
275 | );
276 | }
277 | }
278 |
279 | const form = TestUtils.renderIntoDocument( );
280 |
281 | test.equal(form.refs.formsy.state.isValid, true);
282 | form.addInput();
283 |
284 | immediate(() => {
285 | test.equal(isInValidSpy.called, true);
286 | test.done();
287 | });
288 |
289 | },
290 |
291 | 'should validate a form when removing an invalid input': function (test) {
292 |
293 | const isValidSpy = sinon.spy();
294 |
295 | class TestForm extends React.Component {
296 | constructor(props) {
297 | super(props);
298 | this.state = {showSecondInput: true};
299 | }
300 | removeInput() {
301 | this.setState({
302 | showSecondInput: false
303 | });
304 | }
305 | render() {
306 | return (
307 |
308 |
309 | {
310 | this.state.showSecondInput ?
311 |
312 | :
313 | null
314 | }
315 |
316 | );
317 | }
318 | }
319 |
320 | const form = TestUtils.renderIntoDocument( );
321 |
322 | test.equal(form.refs.formsy.state.isValid, false);
323 | form.removeInput();
324 |
325 | immediate(() => {
326 | test.equal(isValidSpy.called, true);
327 | test.done();
328 | });
329 |
330 |
331 | },
332 |
333 | 'runs multiple validations': function (test) {
334 |
335 | const ruleA = sinon.spy();
336 | const ruleB = sinon.spy();
337 | Formsy.addValidationRule('ruleA', ruleA);
338 | Formsy.addValidationRule('ruleB', ruleB);
339 |
340 | const form = TestUtils.renderIntoDocument(
341 |
342 |
343 |
344 | );
345 |
346 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
347 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
348 | test.equal(ruleA.calledWith({one: 'bar'}, 'bar', true), true);
349 | test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true);
350 | test.done();
351 |
352 | }
353 |
354 | },
355 |
356 | 'should not trigger onChange when form is mounted': function (test) {
357 |
358 |
359 | const hasChanged = sinon.spy();
360 | const TestForm = React.createClass({
361 | render() {
362 | return ;
363 | }
364 | });
365 | TestUtils.renderIntoDocument( );
366 | test.equal(hasChanged.called, false);
367 | test.done();
368 |
369 | },
370 |
371 | 'should trigger onChange once when form element is changed': function (test) {
372 |
373 | const hasChanged = sinon.spy();
374 | const form = TestUtils.renderIntoDocument(
375 |
376 |
377 |
378 | );
379 | TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}});
380 | test.equal(hasChanged.calledOnce, true);
381 | test.done();
382 |
383 | },
384 |
385 | 'should trigger onChange once when new input is added to form': function (test) {
386 |
387 | const hasChanged = sinon.spy();
388 | const TestForm = React.createClass({
389 | getInitialState() {
390 | return {
391 | showInput: false
392 | };
393 | },
394 | addInput() {
395 | this.setState({
396 | showInput: true
397 | })
398 | },
399 | render() {
400 | return (
401 |
402 | {
403 | this.state.showInput ?
404 |
405 | :
406 | null
407 | }
408 | );
409 | }
410 | });
411 |
412 | const form = TestUtils.renderIntoDocument( );
413 | form.addInput();
414 | immediate(() => {
415 | test.equal(hasChanged.calledOnce, true);
416 | test.done();
417 | });
418 |
419 | },
420 |
421 | 'Update a form': {
422 |
423 | 'should allow elements to check if the form is disabled': function (test) {
424 |
425 | const TestForm = React.createClass({
426 | getInitialState() { return { disabled: true }; },
427 | enableForm() { this.setState({ disabled: false }); },
428 | render() {
429 | return (
430 |
431 |
432 | );
433 | }
434 | });
435 |
436 | const form = TestUtils.renderIntoDocument( );
437 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
438 | test.equal(input.isFormDisabled(), true);
439 |
440 | form.enableForm();
441 | immediate(() => {
442 | test.equal(input.isFormDisabled(), false);
443 | test.done();
444 | });
445 |
446 | },
447 |
448 | 'should be possible to pass error state of elements by changing an errors attribute': function (test) {
449 |
450 | const TestForm = React.createClass({
451 | getInitialState() { return { validationErrors: { foo: 'bar' } }; },
452 | onChange(values) {
453 | this.setState(values.foo ? { validationErrors: {} } : { validationErrors: {foo: 'bar'} });
454 | },
455 | render() {
456 | return (
457 |
458 |
459 | );
460 | }
461 | });
462 | const form = TestUtils.renderIntoDocument( );
463 |
464 | // Wait for update
465 | immediate(() => {
466 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
467 | test.equal(input.getErrorMessage(), 'bar');
468 | input.setValue('gotValue');
469 |
470 | // Wait for update
471 | immediate(() => {
472 | test.equal(input.getErrorMessage(), null);
473 | test.done();
474 | });
475 | });
476 |
477 | },
478 |
479 | 'should trigger an onValidSubmit when submitting a valid form': function (test) {
480 |
481 | let isCalled = sinon.spy();
482 | const TestForm = React.createClass({
483 | render() {
484 | return (
485 |
486 |
487 | );
488 | }
489 | });
490 | const form = TestUtils.renderIntoDocument( );
491 | const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm);
492 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm));
493 | test.equal(isCalled.called,true);
494 | test.done();
495 |
496 | },
497 |
498 | 'should trigger an onInvalidSubmit when submitting an invalid form': function (test) {
499 |
500 | let isCalled = sinon.spy();
501 | const TestForm = React.createClass({
502 | render() {
503 | return (
504 |
505 |
506 | );
507 | }
508 | });
509 | const form = TestUtils.renderIntoDocument( );
510 |
511 | const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm);
512 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm));
513 | test.equal(isCalled.called, true);
514 |
515 | test.done();
516 |
517 | }
518 |
519 | },
520 |
521 | 'value === false': {
522 |
523 | 'should call onSubmit correctly': function (test) {
524 |
525 | const onSubmit = sinon.spy();
526 | const TestForm = React.createClass({
527 | render() {
528 | return (
529 |
530 |
531 | Save
532 |
533 | );
534 | }
535 | });
536 |
537 | const form = TestUtils.renderIntoDocument( );
538 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
539 | test.equal(onSubmit.calledWith({foo: false}), true);
540 | test.done();
541 |
542 | },
543 |
544 | 'should allow dynamic changes to false': function (test) {
545 |
546 | const onSubmit = sinon.spy();
547 | const TestForm = React.createClass({
548 | getInitialState() {
549 | return {
550 | value: true
551 | };
552 | },
553 | changeValue() {
554 | this.setState({
555 | value: false
556 | });
557 | },
558 | render() {
559 | return (
560 |
561 |
562 | Save
563 |
564 | );
565 | }
566 | });
567 |
568 | const form = TestUtils.renderIntoDocument( );
569 | form.changeValue();
570 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
571 | test.equal(onSubmit.calledWith({foo: false}), true);
572 | test.done();
573 |
574 | },
575 |
576 | 'should say the form is submitted': function (test) {
577 |
578 | const TestForm = React.createClass({
579 | render() {
580 | return (
581 |
582 |
583 | Save
584 |
585 | );
586 | }
587 | });
588 | const form = TestUtils.renderIntoDocument( );
589 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
590 | test.equal(input.isFormSubmitted(), false);
591 | TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
592 | test.equal(input.isFormSubmitted(), true);
593 | test.done();
594 |
595 | },
596 |
597 | 'should be able to reset the form to its pristine state': function (test) {
598 |
599 | const TestForm = React.createClass({
600 | getInitialState() {
601 | return {
602 | value: true
603 | };
604 | },
605 | changeValue() {
606 | this.setState({
607 | value: false
608 | });
609 | },
610 | render() {
611 | return (
612 |
613 |
614 | Save
615 |
616 | );
617 | }
618 | });
619 | const form = TestUtils.renderIntoDocument( );
620 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
621 | const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
622 | test.equal(input.getValue(), true);
623 | form.changeValue();
624 | test.equal(input.getValue(), false);
625 | formsyForm.reset();
626 | test.equal(input.getValue(), true);
627 |
628 | test.done();
629 |
630 | },
631 |
632 | 'should be able to reset the form using custom data': function (test) {
633 |
634 | const TestForm = React.createClass({
635 | getInitialState() {
636 | return {
637 | value: true
638 | };
639 | },
640 | changeValue() {
641 | this.setState({
642 | value: false
643 | });
644 | },
645 | render() {
646 | return (
647 |
648 |
649 | Save
650 |
651 | );
652 | }
653 | });
654 | const form = TestUtils.renderIntoDocument( );
655 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
656 | const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
657 |
658 | test.equal(input.getValue(), true);
659 | form.changeValue();
660 | test.equal(input.getValue(), false);
661 | formsyForm.reset({
662 | foo: 'bar'
663 | });
664 | test.equal(input.getValue(), 'bar');
665 | test.done();
666 |
667 | }
668 |
669 | },
670 |
671 | 'should be able to reset the form to empty values': function (test) {
672 |
673 | const TestForm = React.createClass({
674 | render() {
675 | return (
676 |
677 |
678 | Save
679 |
680 | );
681 | }
682 | });
683 | const form = TestUtils.renderIntoDocument( );
684 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
685 | const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
686 |
687 | formsyForm.reset({
688 | foo: ''
689 | });
690 | test.equal(input.getValue(), '');
691 | test.done();
692 |
693 | },
694 |
695 | '.isChanged()': {
696 |
697 | 'initially returns false': function (test) {
698 |
699 | const hasOnChanged = sinon.spy();
700 | const form = TestUtils.renderIntoDocument(
701 |
702 |
703 |
704 | );
705 | test.equal(form.isChanged(), false);
706 | test.equal(hasOnChanged.called, false);
707 | test.done();
708 |
709 | },
710 |
711 | 'returns true when changed': function (test) {
712 |
713 | const hasOnChanged = sinon.spy();
714 | const form = TestUtils.renderIntoDocument(
715 |
716 |
717 |
718 | );
719 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
720 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
721 | test.equal(form.isChanged(), true);
722 | test.equal(hasOnChanged.calledWith({one: 'bar'}), true);
723 | test.done();
724 |
725 | },
726 |
727 | 'returns false if changes are undone': function (test) {
728 |
729 | const hasOnChanged = sinon.spy();
730 | const form = TestUtils.renderIntoDocument(
731 |
732 |
733 |
734 | );
735 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
736 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
737 | test.equal(hasOnChanged.calledWith({one: 'bar'}, true), true);
738 |
739 | TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'foo'}});
740 | test.equal(form.isChanged(), false);
741 | test.equal(hasOnChanged.calledWith({one: 'foo'}, false), true);
742 | test.done();
743 |
744 | }
745 |
746 | }
747 |
748 | };
749 |
--------------------------------------------------------------------------------
/tests/Rules-equals-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 | import immediate from './utils/immediate';
4 |
5 | import Formsy from './..';
6 | import { InputFactory } from './utils/TestInput';
7 |
8 | const TestInput = InputFactory({
9 | render() {
10 | return ;
11 | }
12 | });
13 |
14 | const TestForm = React.createClass({
15 | render() {
16 | return (
17 |
18 |
19 |
20 | );
21 | }
22 | });
23 |
24 | export default {
25 |
26 | 'should pass when the value is equal': function (test) {
27 |
28 | const form = TestUtils.renderIntoDocument( );
29 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
30 | test.equal(inputComponent.isValid(), true);
31 | test.done();
32 |
33 | },
34 |
35 | 'should fail when the value is not equal': function (test) {
36 |
37 | const form = TestUtils.renderIntoDocument( );
38 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
39 | test.equal(inputComponent.isValid(), false);
40 | test.done();
41 |
42 | },
43 |
44 | 'should pass with an empty string': function (test) {
45 |
46 | const form = TestUtils.renderIntoDocument();
47 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
48 | test.equal(inputComponent.isValid(), true);
49 | test.done();
50 |
51 | },
52 |
53 | 'should pass with an undefined': function (test) {
54 |
55 | const form = TestUtils.renderIntoDocument();
56 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
57 | test.equal(inputComponent.isValid(), true);
58 | test.done();
59 |
60 | },
61 |
62 | 'should pass with a null': function (test) {
63 |
64 | const form = TestUtils.renderIntoDocument();
65 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
66 | test.equal(inputComponent.isValid(), true);
67 | test.done();
68 |
69 | },
70 |
71 | 'should fail with a number': function (test) {
72 |
73 | const form = TestUtils.renderIntoDocument();
74 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
75 | test.equal(inputComponent.isValid(), false);
76 | test.done();
77 |
78 | }
79 |
80 | };
81 |
--------------------------------------------------------------------------------
/tests/Rules-isAlpha-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with a string is only latin letters': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should fail with a string with numbers': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), false);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with an undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with a null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an empty string': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should fail with a number': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), false);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-isAlphanumeric-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with a string is only latin letters': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should fail with a string with numbers': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with an undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with a null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an empty string': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with a number': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | },
87 |
88 | 'should fail with a non alpha and number symbols': function (test) {
89 |
90 | const value = '!@#$%^&*()';
91 | const form = TestUtils.renderIntoDocument();
92 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
93 | test.equal(inputComponent.isValid(), false);
94 | test.done();
95 |
96 | }
97 |
98 | };
99 |
--------------------------------------------------------------------------------
/tests/Rules-isEmail-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should fail with "foo"': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), false);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass with "foo@foo.com"': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with an undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with a null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an empty string': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should fail with a number': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), false);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-isEmptyString-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), false);
30 | test.done();
31 |
32 | },
33 |
34 | 'should fail with non-empty string': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), false);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass with an empty string': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should fail with undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), false);
57 | test.done();
58 |
59 | },
60 |
61 | 'should fail with null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), false);
66 | test.done();
67 |
68 | },
69 |
70 | 'should fail with a number': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), false);
75 | test.done();
76 |
77 | },
78 |
79 | 'should fail with a zero': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), false);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-isExisty-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), false);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with a string': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass with an empty string': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should fail with undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), false);
57 | test.done();
58 |
59 | },
60 |
61 | 'should fail with null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), false);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with a number': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with a zero': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-isFloat-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with an empty string': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should fail with a string': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), false);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with a number as string': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument( );
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should fail string with digits': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument( );
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), false);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an int': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with a float': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | },
87 |
88 | 'should pass with a float in science notation': function (test) {
89 |
90 |
91 | const form = TestUtils.renderIntoDocument( );
92 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
93 | test.equal(inputComponent.isValid(), true);
94 | test.done();
95 |
96 | },
97 |
98 | 'should pass with undefined': function (test) {
99 |
100 | const form = TestUtils.renderIntoDocument();
101 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
102 | test.equal(inputComponent.isValid(), true);
103 | test.done();
104 |
105 | },
106 |
107 | 'should pass with null': function (test) {
108 |
109 | const form = TestUtils.renderIntoDocument();
110 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
111 | test.equal(inputComponent.isValid(), true);
112 | test.done();
113 |
114 | },
115 |
116 | 'should pass with a zero': function (test) {
117 |
118 | const form = TestUtils.renderIntoDocument();
119 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
120 | test.equal(inputComponent.isValid(), true);
121 | test.done();
122 |
123 | }
124 |
125 | };
126 |
--------------------------------------------------------------------------------
/tests/Rules-isInt-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with an empty string': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should fail with a string': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), false);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with a number as string': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument( );
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should fail string with digits': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument( );
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), false);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an int': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should fail with a float': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), false);
84 | test.done();
85 |
86 | },
87 |
88 | 'should fail with a float in science notation': function (test) {
89 |
90 |
91 | const form = TestUtils.renderIntoDocument( );
92 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
93 | test.equal(inputComponent.isValid(), false);
94 | test.done();
95 |
96 | },
97 |
98 | 'should pass with undefined': function (test) {
99 |
100 | const form = TestUtils.renderIntoDocument();
101 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
102 | test.equal(inputComponent.isValid(), true);
103 | test.done();
104 |
105 | },
106 |
107 | 'should pass with null': function (test) {
108 |
109 | const form = TestUtils.renderIntoDocument();
110 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
111 | test.equal(inputComponent.isValid(), true);
112 | test.done();
113 |
114 | },
115 |
116 | 'should pass with a zero': function (test) {
117 |
118 | const form = TestUtils.renderIntoDocument();
119 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
120 | test.equal(inputComponent.isValid(), true);
121 | test.done();
122 |
123 | }
124 |
125 | };
126 |
--------------------------------------------------------------------------------
/tests/Rules-isLength-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'isLength:3': {
26 |
27 | 'should pass with a default value': function (test) {
28 |
29 | const form = TestUtils.renderIntoDocument( );
30 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
31 | test.equal(inputComponent.isValid(), true);
32 | test.done();
33 |
34 | },
35 |
36 | 'should fail with a string too small': function (test) {
37 |
38 | const form = TestUtils.renderIntoDocument( );
39 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
40 | test.equal(inputComponent.isValid(), false);
41 | test.done();
42 |
43 | },
44 |
45 | 'should fail with a string too long': function (test) {
46 |
47 | const form = TestUtils.renderIntoDocument( );
48 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
49 | test.equal(inputComponent.isValid(), false);
50 | test.done();
51 |
52 | },
53 |
54 | 'should pass with matching length': function (test) {
55 |
56 | const form = TestUtils.renderIntoDocument( );
57 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
58 | test.equal(inputComponent.isValid(), true);
59 | test.done();
60 |
61 | },
62 |
63 | 'should pass with undefined': function (test) {
64 |
65 | const form = TestUtils.renderIntoDocument();
66 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
67 | test.equal(inputComponent.isValid(), true);
68 | test.done();
69 |
70 | },
71 |
72 | 'should pass with null': function (test) {
73 |
74 | const form = TestUtils.renderIntoDocument();
75 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
76 | test.equal(inputComponent.isValid(), true);
77 | test.done();
78 |
79 | },
80 |
81 | 'should pass with empty string': function (test) {
82 |
83 | const form = TestUtils.renderIntoDocument( );
84 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
85 | test.equal(inputComponent.isValid(), true);
86 | test.done();
87 |
88 | },
89 |
90 | 'should fail with a number': function (test) {
91 |
92 | const form = TestUtils.renderIntoDocument();
93 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
94 | test.equal(inputComponent.isValid(), false);
95 | test.done();
96 |
97 | }
98 |
99 | },
100 |
101 | 'isLength:0': {
102 |
103 | 'should pass with a default value': function (test) {
104 |
105 | const form = TestUtils.renderIntoDocument( );
106 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
107 | test.equal(inputComponent.isValid(), true);
108 | test.done();
109 |
110 | },
111 |
112 | 'should fail with a string too small': function (test) {
113 |
114 | const form = TestUtils.renderIntoDocument( );
115 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
116 | test.equal(inputComponent.isValid(), false);
117 | test.done();
118 |
119 | },
120 |
121 | 'should fail with a string too long': function (test) {
122 |
123 | const form = TestUtils.renderIntoDocument( );
124 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
125 | test.equal(inputComponent.isValid(), false);
126 | test.done();
127 |
128 | },
129 |
130 | 'should pass with matching length': function (test) {
131 |
132 | const form = TestUtils.renderIntoDocument( );
133 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
134 | test.equal(inputComponent.isValid(), true);
135 | test.done();
136 |
137 | },
138 |
139 | 'should pass with undefined': function (test) {
140 |
141 | const form = TestUtils.renderIntoDocument();
142 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
143 | test.equal(inputComponent.isValid(), true);
144 | test.done();
145 |
146 | },
147 |
148 | 'should pass with null': function (test) {
149 |
150 | const form = TestUtils.renderIntoDocument();
151 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
152 | test.equal(inputComponent.isValid(), true);
153 | test.done();
154 |
155 | },
156 |
157 | 'should pass with empty string': function (test) {
158 |
159 | const form = TestUtils.renderIntoDocument( );
160 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
161 | test.equal(inputComponent.isValid(), true);
162 | test.done();
163 |
164 | },
165 |
166 | 'should fail with a number': function (test) {
167 |
168 | const form = TestUtils.renderIntoDocument();
169 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
170 | test.equal(inputComponent.isValid(), false);
171 | test.done();
172 |
173 | }
174 |
175 | }
176 |
177 | };
178 |
--------------------------------------------------------------------------------
/tests/Rules-isNumeric-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with an empty string': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should fail with an unempty string': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), false);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with a number as string': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument( );
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should fail with a number as string with not digits': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument( );
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), false);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an int': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with a float': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | },
87 |
88 | 'should fail with a float in science notation': function (test) {
89 |
90 | const form = TestUtils.renderIntoDocument( );
91 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
92 | test.equal(inputComponent.isValid(), false);
93 | test.done();
94 |
95 | },
96 |
97 | 'should pass with an undefined': function (test) {
98 |
99 | const form = TestUtils.renderIntoDocument();
100 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
101 | test.equal(inputComponent.isValid(), true);
102 | test.done();
103 |
104 | },
105 |
106 | 'should pass with a null': function (test) {
107 |
108 | const form = TestUtils.renderIntoDocument();
109 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
110 | test.equal(inputComponent.isValid(), true);
111 | test.done();
112 |
113 | },
114 |
115 | 'should pass with a zero': function (test) {
116 |
117 | const form = TestUtils.renderIntoDocument();
118 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
119 | test.equal(inputComponent.isValid(), true);
120 | test.done();
121 |
122 | }
123 |
124 | };
125 |
--------------------------------------------------------------------------------
/tests/Rules-isUrl-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should fail with "foo"': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), false);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass with "https://www.google.com/"': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should pass with an undefined': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument();
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), true);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with a null': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should fail with a number': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), false);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with an empty string': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument( );
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-isWords-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass with a 1 word': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass with 2 words': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should fail with a string with numbers': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument( );
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), false);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with an undefined': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument();
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with a null': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should fail with a number': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), false);
84 | test.done();
85 |
86 | }
87 |
88 | };
89 |
--------------------------------------------------------------------------------
/tests/Rules-maxLength-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'should pass with a default value': function (test) {
26 |
27 | const form = TestUtils.renderIntoDocument( );
28 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
29 | test.equal(inputComponent.isValid(), true);
30 | test.done();
31 |
32 | },
33 |
34 | 'should pass when a string\'s length is smaller': function (test) {
35 |
36 | const form = TestUtils.renderIntoDocument( );
37 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
38 | test.equal(inputComponent.isValid(), true);
39 | test.done();
40 |
41 | },
42 |
43 | 'should pass when a string\'s length is equal': function (test) {
44 |
45 | const form = TestUtils.renderIntoDocument( );
46 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
47 | test.equal(inputComponent.isValid(), true);
48 | test.done();
49 |
50 | },
51 |
52 | 'should fail when a string\'s length is bigger': function (test) {
53 |
54 | const form = TestUtils.renderIntoDocument( );
55 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
56 | test.equal(inputComponent.isValid(), false);
57 | test.done();
58 |
59 | },
60 |
61 | 'should pass with empty string': function (test) {
62 |
63 | const form = TestUtils.renderIntoDocument( );
64 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
65 | test.equal(inputComponent.isValid(), true);
66 | test.done();
67 |
68 | },
69 |
70 | 'should pass with an undefined': function (test) {
71 |
72 | const form = TestUtils.renderIntoDocument();
73 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
74 | test.equal(inputComponent.isValid(), true);
75 | test.done();
76 |
77 | },
78 |
79 | 'should pass with a null': function (test) {
80 |
81 | const form = TestUtils.renderIntoDocument();
82 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
83 | test.equal(inputComponent.isValid(), true);
84 | test.done();
85 |
86 | },
87 |
88 | 'should fail with a number': function (test) {
89 |
90 | const form = TestUtils.renderIntoDocument();
91 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
92 | test.equal(inputComponent.isValid(), false);
93 | test.done();
94 |
95 | }
96 |
97 | };
98 |
--------------------------------------------------------------------------------
/tests/Rules-minLength-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import { InputFactory } from './utils/TestInput';
6 |
7 | const TestInput = InputFactory({
8 | render() {
9 | return ;
10 | }
11 | });
12 |
13 | const TestForm = React.createClass({
14 | render() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 | });
22 |
23 | export default {
24 |
25 | 'minLength:3': {
26 |
27 | 'should pass with a default value': function (test) {
28 |
29 | const form = TestUtils.renderIntoDocument( );
30 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
31 | test.equal(inputComponent.isValid(), true);
32 | test.done();
33 |
34 | },
35 |
36 | 'should pass when a string\'s length is bigger': function (test) {
37 |
38 | const form = TestUtils.renderIntoDocument( );
39 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
40 | test.equal(inputComponent.isValid(), true);
41 | test.done();
42 |
43 | },
44 |
45 | 'should fail when a string\'s length is smaller': function (test) {
46 |
47 | const form = TestUtils.renderIntoDocument( );
48 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
49 | test.equal(inputComponent.isValid(), false);
50 | test.done();
51 |
52 | },
53 |
54 | 'should pass with empty string': function (test) {
55 |
56 | const form = TestUtils.renderIntoDocument( );
57 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
58 | test.equal(inputComponent.isValid(), true);
59 | test.done();
60 |
61 | },
62 |
63 | 'should pass with an undefined': function (test) {
64 |
65 | const form = TestUtils.renderIntoDocument();
66 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
67 | test.equal(inputComponent.isValid(), true);
68 | test.done();
69 |
70 | },
71 |
72 | 'should pass with a null': function (test) {
73 |
74 | const form = TestUtils.renderIntoDocument();
75 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
76 | test.equal(inputComponent.isValid(), true);
77 | test.done();
78 |
79 | },
80 |
81 | 'should fail with a number': function (test) {
82 |
83 | const form = TestUtils.renderIntoDocument();
84 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
85 | test.equal(inputComponent.isValid(), false);
86 | test.done();
87 |
88 | }
89 |
90 | },
91 |
92 | 'minLength:0': {
93 |
94 | 'should pass with a default value': function (test) {
95 |
96 | const form = TestUtils.renderIntoDocument( );
97 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
98 | test.equal(inputComponent.isValid(), true);
99 | test.done();
100 |
101 | },
102 |
103 | 'should pass when a string\'s length is bigger': function (test) {
104 |
105 | const form = TestUtils.renderIntoDocument( );
106 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
107 | test.equal(inputComponent.isValid(), true);
108 | test.done();
109 |
110 | },
111 |
112 | 'should pass with empty string': function (test) {
113 |
114 | const form = TestUtils.renderIntoDocument( );
115 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
116 | test.equal(inputComponent.isValid(), true);
117 | test.done();
118 |
119 | },
120 |
121 | 'should pass with an undefined': function (test) {
122 |
123 | const form = TestUtils.renderIntoDocument();
124 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
125 | test.equal(inputComponent.isValid(), true);
126 | test.done();
127 |
128 | },
129 |
130 | 'should pass with a null': function (test) {
131 |
132 | const form = TestUtils.renderIntoDocument();
133 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
134 | test.equal(inputComponent.isValid(), true);
135 | test.done();
136 |
137 | },
138 |
139 | 'should fail with a number': function (test) {
140 |
141 | const form = TestUtils.renderIntoDocument();
142 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
143 | test.equal(inputComponent.isValid(), false);
144 | test.done();
145 |
146 | }
147 |
148 | }
149 |
150 | };
151 |
--------------------------------------------------------------------------------
/tests/Utils-spec.js:
--------------------------------------------------------------------------------
1 | import utils from './../src/utils.js';
2 |
3 | export default {
4 |
5 | 'should check equality of objects and arrays': function (test) {
6 |
7 | const objA = { foo: 'bar' };
8 | const objB = { foo: 'bar' };
9 | const objC = [{ foo: ['bar'] }];
10 | const objD = [{ foo: ['bar'] }];
11 | const objE = undefined;
12 | const objF = undefined;
13 | const objG = null;
14 | const objH = null;
15 |
16 | test.equal(utils.isSame(objA, objB), true);
17 | test.equal(utils.isSame(objC, objD), true);
18 | test.equal(utils.isSame(objA, objD), false);
19 |
20 | test.equal(utils.isSame(objE, objF), true);
21 | test.equal(utils.isSame(objA, objF), false);
22 | test.equal(utils.isSame(objE, objA), false);
23 |
24 | test.equal(utils.isSame(objG, objH), true);
25 | test.equal(utils.isSame(objA, objH), false);
26 | test.equal(utils.isSame(objC, objH), false);
27 | test.equal(utils.isSame(objG, objA), false);
28 |
29 | test.equal(utils.isSame(() => {}, () => {}), true);
30 | test.equal(utils.isSame(objA, () => {}), false);
31 | test.equal(utils.isSame(() => {}, objA), false);
32 |
33 | test.done();
34 |
35 | }
36 |
37 | };
38 |
--------------------------------------------------------------------------------
/tests/Validation-spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TestUtils from 'react-addons-test-utils';
3 |
4 | import Formsy from './..';
5 | import TestInput, {InputFactory} from './utils/TestInput';
6 | import immediate from './utils/immediate';
7 | import sinon from 'sinon';
8 |
9 | export default {
10 |
11 | 'should reset only changed form element when external error is passed': function (test) {
12 |
13 | const form = TestUtils.renderIntoDocument(
14 | invalidate({ foo: 'bar', bar: 'foo' })}>
15 |
16 |
17 |
18 | );
19 |
20 | const input = TestUtils.scryRenderedDOMComponentsWithTag(form, 'INPUT')[0];
21 | const inputComponents = TestUtils.scryRenderedComponentsWithType(form, TestInput);
22 |
23 | form.submit();
24 | test.equal(inputComponents[0].isValid(), false);
25 | test.equal(inputComponents[1].isValid(), false);
26 |
27 | TestUtils.Simulate.change(input, {target: {value: 'bar'}});
28 | immediate(() => {
29 | test.equal(inputComponents[0].isValid(), true);
30 | test.equal(inputComponents[1].isValid(), false);
31 | test.done();
32 | });
33 |
34 | },
35 |
36 | 'should let normal validation take over when component with external error is changed': function (test) {
37 |
38 | const form = TestUtils.renderIntoDocument(
39 | invalidate({ foo: 'bar' })}>
40 |
41 |
42 | );
43 |
44 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
45 | const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
46 |
47 | form.submit();
48 | test.equal(inputComponent.isValid(), false);
49 |
50 | TestUtils.Simulate.change(input, {target: {value: 'bar'}});
51 | immediate(() => {
52 | test.equal(inputComponent.getValue(), 'bar');
53 | test.equal(inputComponent.isValid(), false);
54 | test.done();
55 | });
56 |
57 | },
58 |
59 | 'should trigger an onValid handler, if passed, when form is valid': function (test) {
60 |
61 | const onValid = sinon.spy();
62 | const onInvalid = sinon.spy();
63 |
64 | TestUtils.renderIntoDocument(
65 |
66 |
67 |
68 | );
69 |
70 | test.equal(onValid.called, true);
71 | test.equal(onInvalid.called, false);
72 | test.done();
73 |
74 | },
75 |
76 | 'should trigger an onInvalid handler, if passed, when form is invalid': function (test) {
77 |
78 | const onValid = sinon.spy();
79 | const onInvalid = sinon.spy();
80 |
81 | TestUtils.renderIntoDocument(
82 |
83 |
84 |
85 | );
86 |
87 | test.equal(onValid.called, false);
88 | test.equal(onInvalid.called, true);
89 | test.done();
90 |
91 | },
92 |
93 | 'should be able to use provided validate function': function (test) {
94 |
95 | let isValid = false;
96 | const CustomInput = InputFactory({
97 | componentDidMount() {
98 | isValid = this.isValid();
99 | }
100 | });
101 | const form = TestUtils.renderIntoDocument(
102 |
103 |
104 |
105 | );
106 |
107 | const input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
108 | test.equal(isValid, true);
109 | test.done();
110 |
111 | },
112 |
113 | 'should provide invalidate callback on onValiSubmit': function (test) {
114 |
115 | const TestForm = React.createClass({
116 | render() {
117 | return (
118 | invalidate({ foo: 'bar' })}>
119 |
120 |
121 | );
122 | }
123 | });
124 |
125 | const form = TestUtils.renderIntoDocument( );
126 |
127 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
128 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
129 | TestUtils.Simulate.submit(formEl);
130 | test.equal(input.isValid(), false);
131 | test.done();
132 |
133 | },
134 |
135 | 'should provide invalidate callback on onInvalidSubmit': function (test) {
136 |
137 | const TestForm = React.createClass({
138 | render() {
139 | return (
140 | invalidate({ foo: 'bar' })}>
141 |
142 |
143 | );
144 | }
145 | });
146 |
147 | const form = TestUtils.renderIntoDocument( );
148 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
149 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
150 | TestUtils.Simulate.submit(formEl);
151 | test.equal(input.getErrorMessage(), 'bar');
152 |
153 | test.done();
154 |
155 | },
156 |
157 | 'should not invalidate inputs on external errors with preventExternalInvalidation prop': function (test) {
158 |
159 | const TestForm = React.createClass({
160 | render() {
161 | return (
162 | invalidate({ foo: 'bar' })}>
165 |
166 |
167 | );
168 | }
169 | });
170 |
171 | const form = TestUtils.renderIntoDocument( );
172 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
173 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
174 | TestUtils.Simulate.submit(formEl);
175 | test.equal(input.isValid(), true);
176 | test.done();
177 |
178 | },
179 |
180 | 'should invalidate inputs on external errors without preventExternalInvalidation prop': function (test) {
181 |
182 | const TestForm = React.createClass({
183 | render() {
184 | return (
185 | invalidate({ foo: 'bar' })}>
186 |
187 |
188 | );
189 | }
190 | });
191 |
192 | const form = TestUtils.renderIntoDocument( );
193 | const formEl = TestUtils.findRenderedDOMComponentWithTag(form, 'form');
194 | const input = TestUtils.findRenderedComponentWithType(form, TestInput);
195 | TestUtils.Simulate.submit(formEl);
196 | test.equal(input.isValid(), false);
197 | test.done();
198 |
199 | }
200 |
201 | };
202 |
--------------------------------------------------------------------------------
/tests/utils/TestInput.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Formsy from './../..';
3 |
4 | const defaultProps = {
5 | mixins: [Formsy.Mixin],
6 | getDefaultProps() {
7 | return { type: 'text' };
8 | },
9 | updateValue(event) {
10 | this.setValue(event.target[this.props.type === 'checkbox' ? 'checked' : 'value']);
11 | },
12 | render() {
13 | return ;
14 | }
15 | };
16 |
17 | export function InputFactory(props) {
18 | return React.createClass(Object.assign(defaultProps, props));
19 | }
20 |
21 | export default React.createClass(defaultProps);
22 |
--------------------------------------------------------------------------------
/tests/utils/TestInputHoc.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { HOC as formsyHoc } from './../..';
3 |
4 | const defaultProps = {
5 | methodOnWrappedInstance(param) {
6 | return param;
7 | },
8 | render() {
9 | return ( );
10 | },
11 | };
12 |
13 | export default formsyHoc(React.createClass(defaultProps));
14 |
--------------------------------------------------------------------------------
/tests/utils/immediate.js:
--------------------------------------------------------------------------------
1 | export default function (fn) {
2 | setTimeout(fn, 0);
3 | }
4 |
--------------------------------------------------------------------------------
/webpack.production.config.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 |
3 | module.exports = {
4 |
5 | devtool: 'source-map',
6 | entry: path.resolve(__dirname, 'src', 'main.js'),
7 | externals: 'react',
8 | output: {
9 | path: path.resolve(__dirname, 'release'),
10 | filename: 'formsy-react.js',
11 | libraryTarget: 'umd',
12 | library: 'Formsy'
13 | },
14 | module: {
15 | loaders: [
16 | { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
17 | { test: /\.json$/, loader: 'json' }
18 | ]
19 | }
20 |
21 | };
22 |
--------------------------------------------------------------------------------