react-valiform-base v1.2.3
#React Valiform Base
This package provides an easy and mostly autonomous way of managing and validating forms in React.
##The Form Element
The main component in Valiform is the FormValidate
component. This element creates <form>
tag and manages the state
and potential actions of the entire form itself.
###Usage
To start a new form you simply import and use the ValidateForm
component.
import React from 'react';
import ValidateForm from 'react-valiform-base';
const LoginForm = ({}) => {
return (
<ValidateForm>
...
</ValidateForm>
);
};
On it's own it doesn't do much, but with a combination of props and children it can serve as fully self contained form.
###Props
This is an extensive list of all the props that can be passed to ValidateForm
:
####onSubmit void func(object values)
This callback is triggered whenever a submit button is pressed or when the user pressed enter.
If the form has validation in it's children then the onSubmit
callback will only be triggered when all fields are valid.\
The values
passed the the callback is an object with all fields in the form.
####values object
If you want the form to have a more controlled state, you can pass it an object to values
. This object will then be
the state of the form and any changes will reflect in the form itself. When this prop is set the user cannot change
the fields in the form unless the onChange
prop is implemented and used to change the values
object.
####onChange void func(object values)
This function is triggered on every change in the form. It passed the new state (after the user input) as a parameter.
This function can be used to change a controlled state.
####onElementChange void func(string name, any value)
This function is similar to onChange
. It is triggered on every change, but instead of passing the entire new state
it passed the name of the changed element (name
prop of the input), and the new value.
####isValid void func(bool valid)
This callback is triggered after each render. It returns a value indicating if the form is currently valid.\
Keep in mind that since this is evaluated after update, it will be one render loop out of date as default.
####showErrors bool
This prop tells the form and all of the inputs if they should display any current errors. If not set then the form will
only start displaying errors after the first failed submit.
####clear bool
(false
)
If set to true then the form will be cleared of all data on a successful submit.
####child bool
(false
)
This changes the implementation of the form to use a <div>
tag instead of a <form>
tag. This removed the ability
for submitOnEnter
but also helps fixing errors caused by nested <form>
tags.
####submitOnEnter bool
(true
)
If set to true then the form van be submitted by pressing enter in any conventional input (eg. <input>
tags).
####className string
This works as expected and adds one or more classes to the <form>
/<div>
root element.
The Input Elements
A form without any actual inputs is not of much use. In the base version of this package you have to create your own input elements using one of two higher order functions. One function is for creating input elements and the other is for creating submit buttons.
###Buttons
To create a new submit button you use the component ButtonBuilder(func render)
function. This is a higher order function that accepts a
single parameter and returns a component. The parameter is a render function (component func({classNames, onClick, ...props})
).
The component returned by ButtonBuilder
will function as a button component to be used as a submit button in your forms.
The render function accepts an object with:
####classNames string[]
This prop is a list of classes that should be applied to the rendered button. You can add classes to it using
classNames.push("new-class");
and should be applied like so
<button className={classNames.join(" ")}/>
####onClick void func()
This function should be hooked up to your button's onClick
prop. This function is what triggers the submit logic in the form.
####...props any
The rest of the properties passed to the render function are the props that you end up using when using the button inside of a form.
You can use these props to implement custom features or configurations.
###Inputs
To create a new input component you use the compoennt InputBuilder(string name, func render, object options)
function.
This is a higher order function that accepts a unique name for the type of input, a function to render the input and an object with options.
The only option available is validationRules
. validationRules
should be an object with all the validation rules available for the component.
For more info on this see the Validation section.\
The render
function should render the component and implement some or all of the props provided by Valiform:
({name, title, placeholer, value, error, required, classNames, onChange, submitOnEnter, deferred, ...props}) => {
return <Component/>
}
####name string
This is the name
passed to the input. The name is also the key used in the form state object.
####title string
The title
is a string used to name the field. If no title is passed to the component then it will be the name
with
the first letter uppercased.
####placeholder string
This is a string that can be used as a placeholder. If a placeholder is not passed to the component then it will be the name
with
the first letter uppercased.
####value any
This is the current value of the field.
####error string|null
This prop will be null if there either is no error or if errors are hidden. If an error should be displayed then it will
be a string describing the error.
####required bool
This boolean indicates if the required
rule is being enforced and can be used to add an asterisk to the input title etc.
####classNames string[]
This prop is a list of classes that should be applied to the rendered input. You can add classes to it using
classNames.push("new-class");
and should be applied like so
<input className={classNames.join(" ")}/>
####onChange void func(any value)
onChange
is a function that changes the state of the input. It accepts the new value of the input and immediately updates the value
prop.
####submitOnEnter bool
This bool indicates is the enter action of the field should be disabled or not.
####deferred bool
This is a bool that indicates if a fields changes are being deferred. Meaning that they only take effect after the user pauses for a set
amount of time.
####...props any
The rest of the properties passed to the render function are the props that you end up passing when using the input inside of a form.
You can use these props to implement custom features or configurations.
Using Inputs
ValiForm supplied a a lot of out-of-the-box configuration for your inputs that immediately affect the inputs.
These are the props that you can pass to any input element created by InputBuilder
:
####name string
This is the name of the input in the form state. This works like it would in an uncontrolled form.
Names need to be unique and are required when inside of a ValidateForm
component.
####title string
This is usually a title for the field. It is a human readable name. If nothing is given then one will be created from the name
prop.
####placeholder string
This is a placehodler to show when no value is selected in the input.
If none is given, then one will be auto generated from the name
and title
props.
####deferred bool
This options make it so that the onChange function only is fired after the user stops typing.
It keeps a temporary state internally to handle the only occasional onChange calls.
####value any
This is a per input value that can be used to control the value of an input.
This is mainly used when the input is used outside of a ValidateForm
element.
####onChange void func(any value)
This function is used for a per input controlled state.
It fires when the input updates, and can be used in combination with value
to control an input outside of a ValidateForm
component.
####req|required bool
This boolean sets the field as required and inforces that it has to be filled before the field can be submitted.
####error string
If an error string is given to an input then it will display this error. (only is the render method implements the error
prop).
####showError bool
This boolean can be used to disable the showing of errors on a per input level.
####className string
Works as expected. Add a class to the component.
####locked|disabled bool
Disabled the input. Adds a "locked" class and disables any changed.
####formatChange any func(any value)
This is a function to format the value on every change.
The function accepts the value passed to onChange
and outputs a different value that will be used instead.
A great way to format an input.
####onChangeFunc void func(any value)
A function that is triggered on every change, without grabbing control from the internal state.
The next value is passed.
####rules string|string[]
This is a string or array thereof of rules to enforce as validation.
These rules should be one of the rules passed to the InputBuilder
.
See the Validation section for more info.
####customRules object|object[]
This is an object or array thereof of rules to enforce in the validation.
The custom rules should have the same format as predefined rules defined in the Validation section.
###Examples
Creating a simple submit button:
const FormSubmit = ButtonBuilder(({classNames, onClick, children}) => {
return (
<div className={classNames.join(" ")} onClick={onClick}>
{children}
</div>
);
});
Creating a simple text input:
const FormInput = InputBuilder(({name, title, placeholer, value, error, required, classNames, onChange, submitOnEnter, type}) => {
return (
<div className={classNames.join(" ")}>
<div className="input-head">
<label>{title}{required && <span className="required">*</span>}</label>
{error && <span className="error">{error}</span>}
</div>
<input
type={type || "text"}
name={name || "field"}
value={value || ""}
onKeyDown={e => e.key === "Enter" && !submitOnEnter && e.preventDefault()}
onChange={e => onChange(e.target.value)}
placeholder={placeholder}
/>
</div>
);
});
##Validation A big part of ValiForm is the ability to validate the inputs in the form. In order to do this we need some rules to enforce. The rules are created using a specific syntax, and need to be imported when creating an input.
###Rule Methods There are a set way of checking errors. Each has a name and a number of required settings required.
####regexMatch
regexMatch
takes the value of the field and compares it against a regex expression.
If there is a match then the field is valid, otherwise it is not.\
It requires the field regex
. It should contain the regex expression.
####length
length
takes the length of the value (usually used for strings) and compares it against a set length.
If it's longer then it's valid, otherwise it is not.\
It requires the field length
. It should contain the wanted length.
####compare
compare
strictly compares the new value to another value.
If they are the same then the field is valid, otherwise it is not.\
It requires the field value
. It should contain the value to compare to.
###Rule Syntax
When creating rule you should use a specific syntax.
Every rule is a single object with specific keys.\
Every rule needs a type
prop. This should be one of the rule methods.\
Every rule needs an error
prop. This is the error to display when not valid.\
The rule should also implement props for every required field for the selected type.\
Example:
const veryLong = {
type: "length",
length: 100,
error: "It's not long enough"
};
###Rule Presets
The package comes with some predefined rules defined in baseValidationRules
.
They are as follows:
####email Valid if the value is an email.
####required Valid if the value is longer than 0.
####phone Valid id the value is a danish phone number.
####regNum Valid is the value is a bank registration number.
####accNum Valid is the value is a valid account number.
###Rule Usage
A rule object can either be passed directly to custom rules, or they can be passed to BuildInput
as presets.
If passed as presets then they should be an object where their key is the name of the rule to be used in the rules
prop.
##Example
const LoginForm = ({onLogIn}) => {
return (
<ValidateForm onSubmit={values => onLogIn(values)}>
<div className="login-box">
<FormInput name="email" required rule="email"/>
<hr/>
<FormInput name="password" type="password" required/>
</div>
<FormCheckbox name="remember">
<FormSubmit>Log in</FormSubmit>
</ValidateForm>
);
}