Skip to main content

Component Validators

Each component can have a list of validators attached to it, to ensure that user input is valid when the form is submitted.

Adding a validator to a component

Validators are added as an array on the component when it's defined:

import React, { useState } from "react";
import {
createForm,
textField,
minLength,
StatefulFormView,
} from "@fab4m/fab4m";

const form = createForm({
longtext: textField({
label: "Long text (at least 10 characters)",
validators: [minLength(10)],
}),
});

export default function MinLengthExample() {
const [longText, changeLongText] = useState(undefined);
form.onSubmit((e, data) => {
e.preventDefault();
changeLongText(data.longtext);
});
return (
<div>
<StatefulFormView form={form} />
{longText && (
<div>
<strong>Your long text:</strong> {longText}
</div>
)}
</div>
);
}

Multiple validators

You can combine multiple validators, as an array:

import React, { useState } from "react";
import {
createForm,
textField,
minLength,
allowedValues,
StatefulFormView,
} from "@fab4m/fab4m";

const form = createForm({
longtext: textField({
label:
"Long text (at least 5 characters, valid Values: Water, Juice, Soda)",
validators: [minLength(5), allowedValues(["Water", "Juice", "Soda"])],
}),
});

export default function MinLengthExample() {
const [drink, changeDrink] = useState(undefined);
form.onSubmit((e, data) => {
e.preventDefault();
changeDrink(data.longtext);
});
return (
<div>
<StatefulFormView form={form} />
{drink && (
<div>
<strong>Your drink:</strong> {drink}
</div>
)}
</div>
);
}

Check the validator library

Fab4m comes with several validators, check them out in the Validator reference. Also, check the extension guide on how to create your own validators.