Skip to content

Form Validation #143

@NikZar

Description

@NikZar

I am new to Directus, Vue, Nuxt and AgencyOS. I installed locally the AgencyOS template and I am trying to understand how form validation is implemented.

It seems to me that if I put "required" from the directus studio admin panel in the checkbox field (for accepting term and condtions) the submit button is not handling the validation.
I am also able to submit the contact form with no email provided even though it is required.

I think the UForm.vue file is not checking for field validation in the submitForm() method.

async function submitForm() {
	loading.value = true;

	try {
		await useDirectus(
			createItem('inbox', {
				data: formData,
				form: props.form.id,
			}),
		);

		success.value = true;

		if (props.form.on_success === 'redirect') {
			return navigateTo(props.form.redirect_url);
		}
	} catch (err: any) {
		error.value = err;
	} finally {
		loading.value = false;
	}
}

Am I missing something or is it a feature partially implemented?

I tried to fix it by changing the validate and submitForm methods:

const validate = (state: any): FormError[] => {
	const errors = [];

	if (props.form.schema) {
		for (const field of props.form.schema) {
			if (!state[field.name] && field.validation === 'required'	) {
				errors.push({ path: field.name, message: 'Required' });
			}
		}
	}

	return errors;
};

async function submitForm() {
	loading.value = true;
	error.value = null;

	try {
		var errors = validate(formData);
		if(errors.length > 0) {
			console.log("errors:", errors);
			loading.value = false;
			error.value = "Please fill in all required fields";
			return;
		}

		await useDirectus(
			createItem('inbox', {
				data: formData,
				form: props.form.id,
			}),
		);

		success.value = true;

		if (props.form.on_success === 'redirect') {
			return navigateTo(props.form.redirect_url);
		}
	} catch (err: any) {
		error.value = err;
	} finally {
		loading.value = false;
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions