0

I am trying to make a single method which can be used to update a user profile, to make it easier for a user I want the validation to only work if there is data in the field, however when trying to use the 'sometimes' property with the 'present' property, the validation for string runs for example. in this project I am using vue.js and submit the form data using the inertia.put method, I am also using the vue dev tools chrome extension to view the errors in the inertia prop.

The form object can be seen below

form: {
             name: '',
             username: '',
             email: '',
             password: '',
             password_confirmation: '',
             _token : this.$page.props.csrf
         }

below is the method that will run the put request

Inertia.put(route('user.edit', this.user.id), this.form, {
            onSuccess: () => {
                this.user.username = this.form.username;
                this.form.username = '';
                this.sweetAlertSuccess('username');
            }
        });

this is the validation method in Laravel which is a custom request

public function rules(): array
{
    return [
        'name' => ['sometimes', 'present', 'string', 'max:255'],
        'username' => ['sometimes', 'present', 'max:255', 'string', 'unique:users,username'],
        'email' => ['sometimes', 'present', 'email', 'unique:users,email', 'max:255'],
        'password' => ['sometimes', 'present', 'min:8', 'max:255', 'confirmed']
    ];
}

here is the error message I am seeing, I only want the message to validate the field which has data in it and fails the rules, if the field is empty then I want it to skip the validation for that particular field in the keyed array. enter image description here

1 Answer 1

0

replacing 'present' with nullable fixed the issue.

public function rules(): array
{
    return [
        'name' => ['sometimes', 'nullable', 'string', 'max:255'],
        'username' => ['sometimes','nullable', 'max:255', 'string', 'unique:users,username'],
        'email' => ['sometimes', 'nullable', 'email', 'unique:users,email', 'max:255'],
        'password' => ['sometimes', 'nullable','min:8', 'max:255', 'confirmed']
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.