Skip to content

Feature Request: Support for Early Exit on First Validation Failure #1371

@onepiece-dz

Description

@onepiece-dz

Description:

Hi, I'm using the go-playground/validator package and wanted to suggest a feature that could improve performance, especially when validating large structures with many fields.

Problem:
Currently, when we call validator.Validate.Struct, it performs validation on all fields, even if a field fails validation early. This can cause unnecessary overhead, especially when the structure has many fields. For example, if the first field fails validation, the subsequent fields are still validated, which can be wasteful in terms of both performance and processing time.

Feature Request:
I would like to request an enhancement that allows the validator to stop the validation process immediately when the first validation error occurs. This would provide the ability to exit early, which could significantly improve performance, especially in larger structures or cases where the first failure is the most critical.

Expected Behavior:
If a validation error occurs for any field, the validation process should terminate, and the first error should be returned.
No further fields should be validated once the first error is encountered.

Example Scenario:

type User struct {
    FirstName string `validate:"required"`
    LastName  string `validate:"required"`
    Email     string `validate:"required,email"`
}

user := &User{
    FirstName: "", // This will fail
    LastName:  "Doe",
    Email:     "[email protected]",
}

err := validate.Struct(user)
// On the first validation failure (FirstName), it should stop validation
// and return the error for "FirstName".

Why this is useful:
Performance: Early exit on the first failure would save time by avoiding unnecessary checks on the remaining fields.
Flexibility: It provides the ability to stop processing on the first failure, which is a common use case for many validation scenarios (e.g., form validation, input sanitation).
Compatibility: This feature could be an opt-in behavior, allowing users to opt into "early exit" validation, without breaking current workflows.
Possible Implementation:
This could be achieved by introducing a flag or option, such as WithEarlyExit or similar, that modifies the behavior of the Struct method. When set, it would ensure that the validation process stops after the first error.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions