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

Add message_key to UniqueConstraintValidator for Structured Error Handling #9652

Conversation

m16bappi
Copy link

@m16bappi m16bappi commented Feb 13, 2025

Problem:

The UniqueTogetherValidator previously raised validation errors using the non_related_fields key, leading to inconsistencies in error structures. As a result:

  • Errors were difficult to associate with specific fields in frontend applications.
  • Validation messages were not properly structured, making it challenging to integrate with form-handling logic.
  • When non_related_fields were involved, the error response did not clearly indicate the affected field.

Solution:

  • Introduced a message_key parameter to the UniqueTogetherValidator.
  • If provided, the validation error will be returned as a dictionary with message_key as the key.
  • If message_key is not provided, the error will default to {non_related_field: "The fields race_name, position must make a unique set."} for clarity.

Example

Before (Without message_key)

class ErrorMessageKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = UniquenessTogetherModel
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=UniquenessTogetherModel.objects.all(),
                fields=['race_name', 'position']
            )
        ]

Response:

{
  "non_related_field": ["The fields race_name, position must make a unique set."]
}

After (With message_key="name")

class ErrorMessageKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = UniquenessTogetherModel
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=UniquenessTogetherModel.objects.all(),
                fields=['race_name', 'position'],
                message_key='race_name'
            )
        ]

Response:

{
  "race_name": ["The fields race_name, position must make a unique set."]
}

@auvipy auvipy self-requested a review February 14, 2025 05:41
Copy link
Member

@auvipy auvipy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please mention the related issue please?

@m16bappi
Copy link
Author

m16bappi commented Feb 14, 2025

Related Issue:
Most frontend validation libraries, like Formik, React Hook Form, or VeeValidate (Vue), expect errors to be structured as { fieldName: errorMessage }. If the backend returns an unrelated key (non_related_field), the form library cannot properly associate the error with the correct input.

Example in React Hook Form

const {
  register,
  setError,
  formState: { errors }
} = useForm();

const onSubmit = (data) => {
  axios.post("/submit", data).catch((error) => {
    Object.keys(error.response.data).forEach((key) => {
      setError(key, { type: "server", message: error.response.data[key][0] });
    });
  });
};

return (
  <form onSubmit={handleSubmit(onSubmit)}>
    <label>Race Name:</label>
    <input {...register("race_name")} />
    {errors.race_name && <span>{errors.race_name.message}</span>}

    <label>Position:</label>
    <input {...register("position")} />
    {errors.position && <span>{errors.position.message}</span>}

    <button type="submit">Submit</button>
  </form>
);

Since setError("non_related_field", { message: "..." }) is not linked to any input field, the error does not appear in the form.

This issue makes it difficult to correctly display validation messages in frontend applications that rely on field-specific error keys. Introducing message_key resolves this by allowing developers to specify a relevant field name for the error, ensuring it integrates seamlessly with form validation libraries.

@browniebroke
Copy link
Member

browniebroke commented Feb 14, 2025

Since setError("non_related_field", { message: "..." }) is not linked to any input field, the error does not appear in the form.

As you said, the error isn't linked to a specific input, it's caused by a combination of inputs. Attaching it to a field in your UI might be misleading. I'm not convinced the solution you suggest the right abstraction...

On the other hand, you can change your client code to report non-field errors at the top of the form, a bit like this:

const {
  register,
  setError,
  formState: { errors }
} = useForm();

const onSubmit = (data) => {
  axios.post("/submit", data).catch((error) => {
    Object.keys(error.response.data).forEach((key) => {
      setError(key, { type: "server", message: error.response.data[key][0] });
    });
  });
};

return (
  <form onSubmit={handleSubmit(onSubmit)}>
+    {errors.non_related_field && <span>Global errors:{errors.non_related_field.message}</span>}
    <label>Race Name:</label>
    <input {...register("race_name")} />
    {errors.race_name && <span>{errors.race_name.message}</span>}

    <label>Position:</label>
    <input {...register("position")} />
    {errors.position && <span>{errors.position.message}</span>}

    <button type="submit">Submit</button>
  </form>
);

@m16bappi m16bappi closed this Feb 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants