UNPKG

13.2 kBJavaScriptView Raw
1"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash"),n=t(require("prop-types")),r=t(require("react"));function i(){return(i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function a(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function o(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function u(t){return Array.isArray(t)}function s(t){return e.isPlainObject(t)}function l(t){return t instanceof Date}function d(t){return null!==t&&"function"==typeof t}function c(t){return"string"==typeof t}function f(t){return t instanceof RegExp}function p(t){return""===t}function m(t){return null==t}function v(t){return void 0===t}function h(){}function V(t){return s(t)?i({},t):u(t)?[].concat(t):t}function g(t,e){return typeof t==typeof e&&(u(t)&&u(e)?t.length===e.length&&t.every((function(t,n){return g(t,e[n])})):d(t)&&d(e)||l(t)&&l(e)?t.toString()===e.toString():s(t)&&s(e)?Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every((function(n){return g(t[n],e[n])})):f(t)&&f(e)?t.toString()===e.toString():t===e)}function b(t,e,n,r){var i={errors:[],failed:[],success:[]};return Object.keys(n).forEach((function(a){var o=n[a],u=r[a],s=function(t){c(t)?(i.errors.push(t),i.failed.push(a)):t?i.success.push(a):i.failed.push(a)};if(u&&d(o))throw new Error("Formsy does not allow you to override default validations: "+a);if(!u&&!d(o))throw new Error("Formsy does not have the validation rule: "+a);return d(o)?s(o(e,t)):s(u(e,t,o))})),i}function y(t){return!m(t)}function E(t){return c(t)?p(t):!function(t){return void 0===t}(t)&&v(t)}function F(t){return c(t)?p(t):m(t)}function S(t,e,n){return!y(e)||E(e)||n.test(""+e)}var w=/^[A-Z]+$/i,I=/^[0-9A-Z]+$/i,q=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i,x=/^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][+-]?(?:\d+))?$/,R=/^(?:[-+]?(?:0|[1-9]\d*))$/,C=/^[-+]?(?:\d*[.])?\d+$/,O=/^[\sA-ZÀ-ÖØ-öø-ÿ]+$/i,D=/^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/i,j=/^[A-Z\s]+$/i,M={equals:function(t,e,n){return!y(e)||E(e)||e===n},equalsField:function(t,e,n){return e===t[n]},isAlpha:function(t,e){return S(0,e,w)},isAlphanumeric:function(t,e){return S(0,e,I)},isDefaultRequiredValue:function(t,e){return F(e)},isEmail:function(t,e){return S(0,e,q)},isEmptyString:function(t,e){return E(e)},isExisty:function(t,e){return y(e)},isFalse:function(t,e){return!1===e},isFloat:function(t,e){return S(0,e,x)},isInt:function(t,e){return S(0,e,R)},isLength:function(t,e,n){return!y(e)||E(e)||e.length===n},isNumeric:function(t,e){return function(t){return"number"==typeof t}(e)||S(0,e,C)},isSpecialWords:function(t,e){return S(0,e,O)},isTrue:function(t,e){return!0===e},isUndefined:function(t,e){return v(e)},isUrl:function(t,e){return S(0,e,D)},isWords:function(t,e){return S(0,e,j)},matchRegexp:S,maxLength:function(t,e,n){return!y(e)||e.length<=n},minLength:function(t,e,n){return!y(e)||E(e)||e.length>=n}},P=function(){throw new Error("Could not find Formsy Context Provider. Did you use withFormsy outside <Formsy />?")},A=r.createContext({attachToForm:P,detachFromForm:P,isFormDisabled:!0,isValidValue:P,validate:P,runValidation:P}),T=function(t){return c(t)?t.split(/,(?![^{[]*[}\]])/g).reduce((function(t,e){var n=e.split(":"),r=n.shift();if((n=n.map((function(t){try{return JSON.parse(t)}catch(e){return t}}))).length>1)throw new Error("Formsy does not support multiple args on string validations. Use object format of validations instead.");var a=i({},t);return a[r]=!n.length||n[0],a}),{}):t||{}},N={innerRef:n.func,name:n.string.isRequired,required:n.oneOfType([n.bool,n.object,n.string]),validations:n.oneOfType([n.object,n.string]),value:n.any},k=function(t){function n(n){var r,a,o;return(r=t.call(this,n)||this).prevInputNames=null,r.componentDidMount=function(){r.prevInputNames=r.inputs.map((function(t){return t.props.name})),r.validateForm()},r.componentDidUpdate=function(t){var e=r.props,n=e.validationErrors,a=e.disabled;n&&s(n)&&Object.keys(n).length>0&&r.setInputValidationErrors(n);var o=r.inputs.map((function(t){return t.props.name}));r.prevInputNames&&!g(r.prevInputNames,o)&&(r.prevInputNames=o,r.validateForm()),a!==t.disabled&&r.setState((function(t){return i({},t,{contextValue:i({},t.contextValue,{isFormDisabled:a})})}))},r.getCurrentValues=function(){return r.inputs.reduce((function(t,e){return t[e.props.name]=V(e.state.value),t}),{})},r.getModel=function(){var t=r.getCurrentValues();return r.mapModel(t)},r.getPristineValues=function(){return r.inputs.reduce((function(t,e){var n=e.props;return t[n.name]=V(n.value),t}),{})},r.setFormPristine=function(t){r.setState({formSubmitted:!t}),r.inputs.forEach((function(e){e.setState({formSubmitted:!t,isPristine:t})}))},r.setInputValidationErrors=function(t){var e=r.props.preventExternalInvalidation,n=r.state.isValid;r.inputs.forEach((function(e){var n=e.props.name;e.setState({isValid:!(n in t),validationError:c(t[n])?[t[n]]:t[n]})})),!e&&n&&r.setFormValidState(!1)},r.setFormValidState=function(t){var e=r.props,n=e.onValid,i=e.onInvalid;r.setState({isValid:t}),t?n():i()},r.isValidValue=function(t,e){return r.runValidation(t,e).isValid},r.isFormDisabled=function(){return r.props.disabled},r.mapModel=function(t){var n=r.props.mapping;if(n)return n(t);var i={};return Object.keys(t).forEach((function(n){e.set(i,n,t[n])})),i},r.reset=function(t){r.setFormPristine(!0),r.resetModel(t)},r.resetInternal=function(t){var e=r.props.onReset;t.preventDefault(),r.reset(),e&&e()},r.resetModel=function(t){r.inputs.forEach((function(n){var r=n.props.name;t&&e.has(t,r)?n.setValue(e.get(t,r)):n.resetValue()})),r.validateForm()},r.runValidation=function(t,e){void 0===e&&(e=t.state.value);var n=r.props.validationErrors,i=t.props,a=i.validationError,o=i.validationErrors,u=i.name,s=r.getCurrentValues(),l=b(e,s,t.validations,M),d=b(e,s,t.requiredValidations,M),f=!!Object.keys(t.requiredValidations).length&&!!d.success.length,p=!(l.failed.length||n&&n[t.props.name]);return{isRequired:f,isValid:!f&&p,validationError:function(){if(p&&!f)return r.emptyArray;if(l.errors.length)return l.errors;if(n&&n[u])return c(n[u])?[n[u]]:n[u];if(f){var t=o[d.success[0]]||a;return t?[t]:null}return l.failed.length?l.failed.map((function(t){return o[t]?o[t]:a})).filter((function(t,e,n){return n.indexOf(t)===e})):void 0}()}},r.attachToForm=function(t){-1===r.inputs.indexOf(t)&&r.inputs.push(t),r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged()),r.throttledValidateForm()},r.detachFromForm=function(t){var e=r.inputs.indexOf(t);-1!==e&&(r.inputs=r.inputs.slice(0,e).concat(r.inputs.slice(e+1))),r.validateForm()},r.isChanged=function(){return!g(r.getPristineValues(),r.getCurrentValues())},r.submit=function(t){var e=r.props,n=e.onSubmit,i=e.onValidSubmit,a=e.onInvalidSubmit,o=r.state.isValid;e.preventDefaultSubmit&&t&&t.preventDefault&&t.preventDefault(),r.setFormPristine(!1);var u=r.getModel();n(u,r.resetModel,r.updateInputsWithError,t),o?i(u,r.resetModel,r.updateInputsWithError,t):a(u,r.resetModel,r.updateInputsWithError,t)},r.updateInputsWithError=function(t,e){var n=r.props.preventExternalInvalidation,i=r.state.isValid;Object.entries(t).forEach((function(e){var i=e[0],a=e[1],o=r.inputs.find((function(t){return t.props.name===i}));if(!o)throw new Error("You are trying to update an input that does not exist. Verify errors object with input names. "+JSON.stringify(t));o.setState({isValid:n,validationError:c(a)?[a]:a})})),e&&i&&r.setFormValidState(!1)},r.updateInputsWithValue=function(t,n){r.inputs.forEach((function(r){var i=r.props.name;t&&e.has(t,i)&&r.setValue(e.get(t,i),n)}))},r.validate=function(t){r.state.canChange&&(0,r.props.onChange)(r.getModel(),r.isChanged());var e=r.runValidation(t);t.setState(e,r.validateForm)},r.validateForm=function(){var t=function(){var t=r.inputs.every((function(t){return t.state.isValid}));r.setFormValidState(t),r.setState({canChange:!0})};r.inputs.forEach((function(e,n){var i=r.runValidation(e);e.setState(i,n===r.inputs.length-1?t:null)})),r.inputs.length||r.setState({canChange:!0},t)},r.state={canChange:!1,isSubmitting:!1,isValid:!0,contextValue:{attachToForm:r.attachToForm,detachFromForm:r.detachFromForm,isFormDisabled:n.disabled,isValidValue:r.isValidValue,validate:r.validate,runValidation:r.runValidation}},r.inputs=[],r.emptyArray=[],r.throttledValidateForm=(a=r.validateForm,o=!0,function(){if(o){o=!1;for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];a.apply(this,e),setTimeout((function(){return o=!0}),66)}}),r}return a(n,t),n.prototype.render=function(){var t=this.props,e=t.children,n=t.disabled,a=t.formElement,o=function(t,e){if(null==t)return{};var n,r,i={},a=Object.keys(t);for(r=0;r<a.length;r++)e.indexOf(n=a[r])>=0||(i[n]=t[n]);return i}(t,["children","mapping","onChange","onInvalid","onInvalidSubmit","onReset","onSubmit","onValid","onValidSubmit","preventDefaultSubmit","preventExternalInvalidation","validationErrors","disabled","formElement"]);return r.createElement(A.Provider,{value:this.state.contextValue},r.createElement(a,i({onReset:this.resetInternal,onSubmit:this.submit},o,{disabled:n}),e))},n}(r.Component);k.displayName="Formsy",k.propTypes={disabled:n.bool,mapping:n.func,formElement:n.oneOfType([n.string,n.object,n.func]),onChange:n.func,onInvalid:n.func,onInvalidSubmit:n.func,onReset:n.func,onSubmit:n.func,onValid:n.func,onValidSubmit:n.func,preventDefaultSubmit:n.bool,preventExternalInvalidation:n.bool,validationErrors:n.object},k.defaultProps={disabled:!1,mapping:null,onChange:h,onInvalid:h,onInvalidSubmit:h,onReset:h,onSubmit:h,onValid:h,onValidSubmit:h,preventDefaultSubmit:!0,preventExternalInvalidation:!1,validationErrors:{},formElement:"form"},exports.addValidationRule=function(t,e){M[t]=e},exports.default=k,exports.propTypes=N,exports.validationRules=M,exports.withFormsy=function(t){var e,n=function(e){function n(t){var n;(n=e.call(this,t)||this).getErrorMessage=function(){var t=n.getErrorMessages();return t.length?t[0]:null},n.getErrorMessages=function(){var t=n.state.validationError;return(!n.isValid()||n.showRequired())&&t||[]},n.getValue=function(){return n.state.value},n.setValidations=function(t,e){n.validations=T(t)||{},n.requiredValidations=!0===e?{isDefaultRequiredValue:e}:T(e)},n.setValue=function(t,e){void 0===e&&(e=!0);var r=n.props.validate;e?n.setState({value:t,isPristine:!1},(function(){r(o(n))})):n.setState({value:t})},n.hasValue=function(){return F(n.state.value)},n.isFormDisabled=function(){return n.props.isFormDisabled},n.isFormSubmitted=function(){return n.state.formSubmitted},n.isPristine=function(){return n.state.isPristine},n.isRequired=function(){return!!n.props.required},n.isValid=function(){return n.state.isValid},n.isValidValue=function(t){return n.props.isValidValue(o(n),t)},n.resetValue=function(){var t=n.props.validate;n.setState({value:n.state.pristineValue,isPristine:!0},(function(){t(o(n))}))},n.showError=function(){return!n.showRequired()&&!n.isValid()},n.showRequired=function(){return n.state.isRequired};var r=t.runValidation,a=t.validations,u=t.required;return n.state={value:t.value},n.setValidations(a,u),n.state=i({formSubmitted:!1,isPristine:!0,pristineValue:t.value,value:t.value},r(o(n),t.value)),n}a(n,e);var u=n.prototype;return u.componentDidMount=function(){var t=this.props,e=t.attachToForm;if(!t.name)throw new Error("Form Input requires a name property when used");e(this)},u.shouldComponentUpdate=function(t,e){var n=this.state,r=function(t,e){return Object.keys(t).some((function(n){return t[n]!==e[n]}))},i=r(this.props,t),a=r(n,e);return i||a},u.componentDidUpdate=function(t){var e=this.props,n=e.value,r=e.validations,i=e.required,a=e.validate;g(n,t.value)||this.setValue(n),g(r,t.validations)&&g(i,t.required)||(this.setValidations(r,i),a(this))},u.componentWillUnmount=function(){(0,this.props.detachFromForm)(this)},u.render=function(){var e=this.props.innerRef,n=i({},this.props,{errorMessage:this.getErrorMessage(),errorMessages:this.getErrorMessages(),hasValue:this.hasValue(),isFormDisabled:this.isFormDisabled(),isFormSubmitted:this.isFormSubmitted(),isPristine:this.isPristine(),isRequired:this.isRequired(),isValid:this.isValid(),isValidValue:this.isValidValue,resetValue:this.resetValue,setValidations:this.setValidations,setValue:this.setValue,showError:this.showError(),showRequired:this.showRequired(),value:this.getValue()});return e&&(n.ref=e),r.createElement(t,n)},n}(r.Component);return n.displayName="Formsy("+((e=t).displayName||e.name||(c(e)?e:"Component"))+")",n.propTypes=N,n.defaultProps={innerRef:null,required:!1,validationError:"",validationErrors:{},validations:null,value:t.defaultValue},function(t){return r.createElement(A.Consumer,null,(function(e){return r.createElement(n,i({},t,e))}))}};
2//# sourceMappingURL=formsy-react.cjs.production.min.js.map