Form Validation: useForm Hook
Proposed change
Creating a hook to provide our own validation, including custom validators for IBAN and SSN down the line. At the moment, string, number, date, and account number validators are complete.
The goal is to not have to rely on an outside dependency for form validation when dealing with user input. We also aim to provide validation feedback to the developer in an easy-to-implement way.
The other validation libraries we looked at are either incompatible with Eufemia, require extensive rewrites of our current components, or require extra dependencies to provide the desired functionality.
Therefore we arrived at the conclusion to write our own.
How it looks now
Currently, there is no validation engine in use. The closest would be manually checking the values received and setting a response/error message.
Alternative
From the documentation of the hook:
// Initialization:
import { useForm, string, number } from '@pm-netbank/form-validation';
const { values, errors, onChange, validate } = useForm({
myProperty: string('the default value'),
otherProperty: number()
});
// Usage:
const { values } = useForm({ myProperty: string() });
<input value={values.myProperty} />;
// Hooking the on-change of any component into useForm for instant updates
const { onChange } = useForm({ myProperty: string() });
<input onChange={(event) => onChange.myProperty(event.target.value)} />;
// Errors:
const { errors } = useForm({ myProperty: string().isRequired() });
// errors will be something like [{ type: 'IS_REQUIRED', message: 'The value is required'}]
<div>
{errors.myProperty.map(({ type, message }) => (
<p key={type}>{message}</p>
))}
</div>;
// Performing the validation:
// The validation method goes through each of the defined fields and
// checks if they adhere to all the rules defined for said field.
// Then, any errors are aggregated into the "errors" object.
// We have opted for a manual validation method in order to
// give the developer complete control of when the form is to be
// validated.
// Automatic validation requires a decent amount of work to get right.
// However, if enough people want it, it might make it into the backlog.
const { validate } = useForm({ myProperty: string() });
function beforeSave() {
validate();
}
//This will set the 'isValid' property of useForm to be either true or false
Motivation
Have our own validation engine without relying on external libraries. Also: Being able to add validations easily should the need arise.
We currently do not have many form-like pages in the Netbank, but this is about to change. Therefore, being ahead of the curve ("pro-active", if you will) and offering an in-house validation engine will save the time of those about to look for a way to ensure their forms are valid.
It will also not require a lot of refactoring, since we do not have many forms (yet).
Proposed transition strategy
This hook will not break anything as it is a new internal feature.