@chipp972/form-validation
v1.5.0
Published
Form component and wrapper to connect individual inputs
Downloads
29
Readme
form-validation
Description
Form components to manage validity of form fields.
Examples
import { Form, useForm, hasBetweenChecked } from '@chipp972/form-validation';
import { InputText, CheckboxGroup, Select } from '@chipp972/form';
import { PreviousButton, ValidationButton } from '@chipp972/buttons';
// Wrap the components to have access to validation data and methods
// (hasError, isValid, isInitial, updateFieldState and resetFieldState)
const MyInput = ({ name, validate, errorMessage, label, ...props }) => {
const { hasError } = useForm({ name, validate, errorMessage });
return (
<>
<label htmlFor={name}>
{label}
<input {...props} name={name} id={name} />
</label>
{hasError && <span>{errorMessage}</span>}
</>
);
};
export const MyForm = ({ formElementData, successCallback, failureCallback }) => (
<Form onValidationSuccess={successCallback} onValidationFailure={failureCallback}>
<MyInput
label={formElementData[0].label}
name={formElementData[0].name}
validate={(value) => value === 'test'}
errorMessage={formElementData[0].errorMessage}
/>
<PreviousButton type="reset">Reset</PreviousButton>
<ValidationButton type="submit">Validate</ValidationButton>
</Form>
);
FAQ
Validate input directly
To validate the inputs when mounted just create a class component
with a componentDidMount
lifecycle method or add a useEffect
hook and
trigger updateFieldState
from there.
Trigger validation/reset manually
To validate the form manually get a ref of the Form
component
and trigger formRef.current.submit()
or formRef.current.reset()
.
You can also use a querySelector if you put an id on the form for example:
document.querySelector('#formId')?.requestSubmit()
.
Changelog
1.5.0
- Expose
FieldState
enum - forwardRef of the
Form
component to triggersubmit
andreset
manually
1.4.3
- Use ramda es5 imports
1.4.2
- Fix do not put the values of unchecked checkboxes in the result
1.4.1
- Fix @emotion/core injected in build files
1.4.0
- Expose
filterUseFormProps
to avoid React warnings for invalid props - Add
dependentFields
prop to pass an array of field names that should trigger validation when the field changes
1.3.0
- Add
validateDependencies
to reconnect the field if the validate function has to be updated