We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Best method for validating an individual element within a form

Hi there,

Does anyone know the best method for validating a single form element? Or, if there is a better way to building complex forms in MVC? Just let me know.

The website I am building has complex relationships and forms that can largely be resused with little modifications.

I figure I can initialize the form with all of the elements, and the validators attached to the elements (just as you normally would). Then, rather than validating the form as a whole and submitting the whole form, I would create methods within the form that validate the fields necessary to submit (per method) and submit the form.

So, as a simple example, you could have a UserForm class that contains login(), register(), and resetPassword() methods. The login() method would validate the email and password field, then submit. The register() method would validate the same fields, but also validate company field and then proceed to submit. The resetPassword() field would validate only email. But overall, we make use of the same elements and validation.

There are far more complex examples, but this seems to be a fairly smart use of forms.

Thank you for the reply, but that doesn't answer my question. As I stated, forms can and in MVC should have multiple use cases (scenarios as some would call them). The submit logic according to MVC should also be within the form.

My question requires several parts:

  1. A form contains elements, each with their own validators
  2. There may be multiple methods within a form to submit
  3. Each method that submits within the form must validate its own field requirements.
  4. Each form may have multiple partials for different rendering in different scenarios.

In the end, you have a form class that can be used across a phalcon app, with multiple scenarios and all of the rendering and submission logic in one place. This is a proper use of an MVC form.

So my question is, what is the best way (within a form's methods) to validate specific fields.

class SomeForm

initialize() { // 5 fields and their validators }

someMethod() { // Only uses 3 of the 5 fields // Validate the three fields // created ORM entity(s) and save() }

someOtherMethod() { // Uses all 5 fields // Validate all 5 fields // created ORM entity(s) and save() }