I am using React and JSON Forms to build a form with an input that has a minimum length restriction and an email format. I am unable to generate a custom error message.
The docs say to use ajv-errors
, but I haven't been able to change the error message that appears.
Schema:
export const schema = {
type: 'object',
properties: {
inputControl: {
type: 'string',
format: 'email',
minLength: 7,
},
},
}
UI Schema:
export const uischema = {
type: 'VerticalLayout',
elements: [
{
type: 'Control',
scope: '#/properties/inputControl',
label: 'Please enter your email address',
},
],
}
I have tried using ajv-errors
. I cannot remember exactly what, but nothing worked. i.e. the error message on the screen remains the same.
When I tried adding a keyword from examples on the internet, the linter always tells me that one of the keys is missing or gives some other error.
To define a custom error message using the errorMessage
keyword in your schemas, you should wrap the Ajv instance with ajvErrors
instance.
(note that since you are using format: "email"
I'd assume you are also using the ajv-fromats
package)
import Ajv from "ajv";
import ajvErrors from "ajv-errors";
import ajvFormats from "ajv-formats";
// allErrors must be true when using ajvErrors package
const ajv = ajvFormats(ajvErrors(new Ajv({ allErrors: true })));
export const schema = {
type: "object",
properties: {
inputControl: {
type: "string",
format: "email",
minLength: 7,
errorMessage: "Email is required and must be at least 7 characters long", // or what ever custom message you want to add
},
},
};
...