In your application's root file, you'll configure @nattyjs/tidy to run validation specifically on submit:
import { configure, Validators, RunValidatorStrategy } from "@nattyjs/tidy";
configure({
runValidatorStrategy: RunValidatorStrategy.OnSubmit,
errorMessage: {
validator: {
required: 'this field is required.', // Customize error messages as needed
}
}
});
RunValidatorStrategy.OnSubmit: This setting ensures validators are triggered only when the form is submitted.errorMessage: This object allows you to customize error messages displayed to the user. Here, we've defined a message for the required validator.Here's how you create the userForm object with a validation rule for the name field
const userForm = useForm({ name: '' }, {
validators: {
name: Validators.required(),
}
});
Here's an example onSubmit method that triggers form validation and handles successful or failed submissions:
onSubmit() {
// Set form submission flag (strictly necessary with OnSubmit strategy)
this.userForm.submit = true;
if (this.userForm.valid) {
// Form is valid, proceed with form submission logic (e.g., sending data to server)
console.log('Form submitted successfully!');
} else {
// Form is invalid, display error messages to the user
console.error('Form validation failed:', this.userForm.errors);
// Optionally, display specific error messages near the corresponding form fields
}
}
Explanation:
this.userForm.submit = true; (Optional):console.log('Form submitted successfully!'):console.error('Form validation failed:', this.userForm.errors):this.userForm.errors. You can log this information for debugging or display user-friendly error messages next to the corresponding form fields.