Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I change validation message? #148

Closed
Reload0213 opened this issue Sep 26, 2022 · 8 comments
Closed

How can I change validation message? #148

Reload0213 opened this issue Sep 26, 2022 · 8 comments
Labels
question Further information is requested

Comments

@Reload0213
Copy link

hi, Love your work!

Can I change validation message?

Even though strict mode is turned off, errorMessage and errorMessages of the ajv schema structure are not applied

please help me Thanks!

@josdejong
Copy link
Owner

Thanks. Can you share a minimal code example of what you're trying to do?

@josdejong josdejong added the question Further information is requested label Sep 26, 2022
@Reload0213
Copy link
Author

Reload0213 commented Sep 27, 2022

I want to customize the validation message as desired, or if not, apply the locale where I live.

So, knowing that validation is handled through ajv, I tried the following with reference to it.

const SvelteJSONEditor = ({ props, refEditor }) => {
    const theme = useTheme();

    const refContainer = useRef(null);

    // validation(예시) - 필요한 알림 값 정의 후 적용
    const schema = {
        title: "Employee",
        description: "Object containing employee details",
        type: "object",
        properties: {
            firstName: {
                title: "First Name",
                description: "The given name.",
                examples: ["John"],
                type: "string",
            },
            lastName: {
                title: "Last Name",
                description: "The family name.",
                examples: ["Smith"],
                type: "string", // type 컬럼 타입 설정
                errorMessage: {
                    type: ":lastName:이름을 입력해 주세요",
                },
            },
            gender: {
                title: "Gender",
                enum: ["male", "female"], // enum 컬럼 값 제한
            },
            availableToHire: {
                type: "boolean",
                default: false,
            },
            age: {
                description: "Age in years",
                type: "integer",
                minimum: 0,
                examples: [28, 32],
            },
            job: {
                $ref: "job",
            },
        },
        required: ["firstName", "lastName"], // required 필수 컬럼 설정
        errorMessages: {
            // Change from errorMessage to errorMessages
            type: "should be an object",
            required: {
                firstName: "testesttest1111",
            },
        },
    };

    const schemaDefinitions = {
        job: {
            title: "Job description",
            type: "object",
            required: ["address"],
            properties: {
                company: {
                    type: "string",
                    examples: ["ACME", "Dexter Industries"],
                },
                role: {
                    description: "Job title.",
                    type: "string",
                    examples: ["Human Resources Coordinator", "Software Developer"],
                    default: "Software Developer",
                },
                address: {
                    type: "string",
                },
                salary: {
                    type: "number",
                    minimum: 120,
                    examples: [100, 110, 120],
                },
            },
        },
    };

    const ajvOptions = { allErrors: true, $data: true };

    useEffect(() => {
        // create editor
        try {
            refEditor.current = new JSONEditor({
                target: refContainer.current,
                props: { validator: createAjvValidator(schema, schemaDefinitions, ajvOptions) },
            });
        } catch (err) {
            console.log(`SvelteJSONEditor create editor: ${err}`);
        }

        return () => {
            // destroy editor
            if (refEditor?.current?.destroy) {
                try {
                    refEditor.current.destroy();
                    refEditor.current = null;
                } catch (err) {
                    console.log(`SvelteJSONEditor destroy editor: ${err}`);
                }
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // update props
    useEffect(() => {
        if (refEditor?.current) {
            try {
                refEditor.current.updateProps(props);
            } catch (err) {
                console.log(`SvelteJSONEditor update props: ${err}`);
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props]);

    return (
        <Box
            sx={{
                border: "1px solid #BDBDBD",
                overflow: "hidden",
            }}
        >
            <Box
                sx={{
                    height: "800px",
                    "&.jse-json-node": {
                        backgroundColor: "red !important",
                    },
                }}
                className={
                    theme.palette.mode === "dark" ? "svelte-jsoneditor-react jse-theme-dark" : "svelte-jsoneditor-react"
                }
                ref={refContainer}
            />
        </Box>
    );
};

export default SvelteJSONEditor;

However, the following console was displayed, and when { strictSchema: false } was added to ajvOptions, no error output was output, but the message I wanted was still not obtained.

스크린샷 2022-09-27 오후 12 01 05

@josdejong
Copy link
Owner

I think the error just tells you that your JSON Schema is invalid, it contains an unknown keyword "errorMessages".

The error messages created by Ajv cannot be changed as far as I know. If you want to customize error messages, you'll have to create your own validator function. There is an example of a custom validator here. If I understand you correctly, you would like to run JSON Schema validation but then afterwards change the error messages. To achieve that, you can create a validator that is a little wrapper around the createAjvValidator, just executing the Ajv validator, and then inspecting and adjusting the errors that come out of Ajv.

@Reload0213
Copy link
Author

Your answer has been of great help. It took some time, but I succeeded in creating a custom validator that can deliver the message I want.

thanks a lot !!

@josdejong
Copy link
Owner

🎉 good to hear, thanks for the feedback.

@Reload0213
Copy link
Author

I'd like to ask you one more question.

No matter what value is delivered as a key value of severity to the validation of the currently customized guidance message, it is output like the yellow "warning" format. As before, I want to deliver values with "info", "warning", and "error", so that fatal errors are distinguished and remarkably red.

I wonder if I should deliver a value other than "info", "warning", and "error" to the severity key of the customized inspector or not.

@josdejong
Copy link
Owner

Yes, that is a good suggestion, thanks. Let's discuss that further in #150.

josdejong pushed a commit that referenced this issue Mar 27, 2024
Pass validation severity into UI, see discussion #369 and issues #148 and #150
@josdejong
Copy link
Owner

This has been implemented now in v0.23.1, see #416.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants