Validator
Add a validator to a user step to check the typed value. Return true to accept it, or an error message to show in the input. See User input for more.
import ChatBot, { type Step } from 'react-simple-chatbot';
const validateAge = (value: string) => { const age = Number(value);
if (value.trim() === '' || Number.isNaN(age)) { return 'Please type a number'; } if (age <= 0) { return 'Your age must be positive'; } if (age >= 120) { return `${value}? Come on!`; } return true;};
const steps: Step[] = [ { id: 'question', message: 'How old are you?', trigger: 'age' }, { id: 'age', user: true, validator: validateAge, trigger: 'answer' }, { id: 'answer', message: 'Got it, you are {previousValue} years old.', end: true }];
export default function Validator() { return <ChatBot headerTitle="Validator" steps={steps} />;}How it works
Section titled “How it works”validateAgereceives the typed text as a string and returns an error message when it is empty, not a number, not positive or 120 or more.- The error message replaces the text in the input for a moment, then the typed text comes back so the user can fix it.
- The next step only runs when the validator returns
true.