Home > database >  axios post to find out if data is valid
axios post to find out if data is valid

Time:03-22

OK I am at the end of my day and I am not thinking straight. So this is what I have...

a Laravel controller, send it a username, and it tells me if the username is available, and if it isnt, it gives me a 422 code

public function checkUsername(Request $request) {
        Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:users'],
        ])->validate();
    
        return response()->json([
            'valid' => true,
            'data' => [
                'message' => 'Username is available!'
            ]
        ], 200);
    }

Example of valid response:

{"valid":true,"data":{"message":"Username is available!"}}%

The curl to test is:

curl -X POST -H "Content-Type: application/json" -d '{"name": "bossryan"}' http://127.0.0.1:8000/api/checkusername

Next: I have a frontend Vue using Vee-validate. It does a bunch of things, but I need to add this latest validation into the mix, so if the username is taken (I don't get the valid response from above, it needs to reply with "This username is already taken"

validateUsername(value) {
                // if the field is empty
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^[a-zA-Z0-9_. -]{4,20}$/i;
                if (!regex.test(value)) {
                    return 'This must be a minimum of 4 characters';
                }
                return true;
            },

This is the axios I created but it isnt working:

const isUnique = (value) => {
                    return axios.post('/api/checkusername', { email: value }).then((response) => {
                        // Notice that we return an object containing both a valid property and a data property.
                        return {
                        valid: response.data.valid,
                        data: {
                            message: response.data.message
                            }
                        };
                    });
                };

I know I need to add in axios, but I am just having a heck of a time setting it up and my mind keeps rushing around. I am just looking for someone who can just help me plug in the axios request above //All is good, so I can finish this up.

THANKS FOR THE HELP COMMUNITY!

CodePudding user response:

Vee-validate seems to want a resolved promise for async validation. Axios will reject the promise if the status is >= 400 so you need to handle that accordingly.

Assuming when validation fails that the response body matches the same { valid, data: { message } } format, you'd want something like the following

const isUnique = (name) => 
  axios.post("/api/checkusername", { name })
    .then(({ data }) => data)
    .catch(err => ({ // resolve with error details
      valid: err.response?.data?.valid ?? false,
      data: {
        // get the message from the response if it exists
        message: err.response?.data?.data?.message ?? "Validation failed"
      }
    }));

export default {
  methods: {
    async validateUsername(value) {
      // do your synchronous checks as per question

      const check = await isUnique(value);
      return check.valid || check.data.message;
    }
  }
}

This will provide a generic message "Validation failed" if the 422 response body doesn't match expectations.

  • Related