jellydator / validation

An idiomatic validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
39 stars 6 forks source link

Conditional rule not working #20

Closed e200 closed 1 year ago

e200 commented 1 year ago

This is my mode and validation receiver:


type UserSignup struct {
    ID        int        `json:"id"`
    FirstName string     `json:"first_name"`
    LastName  *string    `json:"last_name"`
    Username  *string    `json:"username"`
    Email     *string    `json:"email"`
    Phone     *string    `json:"phone"`
    Password  string    `json:"password"`
    PasswordConfirmation string `json:"password_confirmation"`
    CreatedAt *time.Time `json:"created_at"`
}

func (u *UserSignup) Validate() error {
    return validation.ValidateStruct(
        u,
        validation.Field(
            &u.FirstName,
            validation.Required,
            validation.Length(3, 80),
        ),
        validation.Field(&u.LastName, validation.Length(3, 80)),
        validation.Field(&u.Username, validation.Length(3, 20)),
        validation.Field(&u.Email, is.Email, validation.When(
            &u.Phone == nil,
            validation.Required,
        )),
        validation.Field(&u.Phone, is.E164, validation.When(
            &u.Email == nil,
            validation.Required,
        )),
        validation.Field(
            &u.Password,
            validation.Required,
            validation.Length(6, 0),
        ),
        validation.Field(
            &u.PasswordConfirmation,
            validation.Length(6, 0),
            validation.Required,
            validation.When(
                u.Password != u.PasswordConfirmation,
                validation.Required.Error("must be equal to `password`"),
            ),
        ),
    )
}

This is the validation call:

if err := validation.Validate(userSignup); err != nil {
        return err
}

These are the call args and the error:

Screenshot 2023-10-05 at 13 04 28

What is happening?

Validation is returning first_name -> the length must be between 3 and 80 only

What should happen?

Validation should return email or phone is required and also password_confirmations must be equal to password