Web Hosting Forum - Net Hosting Talk

We are a community of individuals and businesses passionate about web hosting. Let's build, learn, and grow together.

JavaScript frontend validation and checking the duplicate username

Andrewsed

Novice
Member
Hello,

I have created a User form in React. In the validation section, I have a front-end validation test using Zod. But while that's happening, I want to check against the database if there are duplicate usernames, but I want it to run parallel to the Zod validation. When Zod validation is finished, I want to check if the fetch was complete and not continue further. If the fetch is still happening, what do I do?

JavaScript:
let zodSchema = z.object({
    name: z.string().min(3).max(12),
    email: z.string().email(),
    password: z.string().min(6),
})

let initialValues = {
    name: '',
    email: '',
    password: '',
}

function validateForm() {

    const zodValidationTest = zodSchema.safeParse(formValues)

    if (!zodValidationTest.success) {
        let errors = zodValidationTest.error.formErrors.fieldErrors
        setFormErrors(errors)
        return
    }



    // validation passed

    setFormErrors(initialValues)
    fetchCreateUser()
}

async function doesUsernameExist() {
    // check duplicate username ...

    return true
    return false
}
 
zod validation would take milliseconds, if that, with a schema that simple. Why make it needlessly complex running them in parallel?

looks like it's synchronous anyway, so just call doesUsernameExist after the if
(!zodValidationTest.success) { ... } block
 
  • Advertisement
  • Advertisement

    Back
    Top