Monday, November 2, 2009

single-field validation from controller

Hello everyone,

let me quickly explain my situation and what i'm trying to achieve.

I have a User model with 5 fields having validation rules, out of
these 5, 3 are required ( required => true, and they also have the
notEmpty rule )

I would like to pre-validate each field, one by one, from the
controller and give a JSON response. The reason for this, as you have
probably already guessed, is that i'm validating dynamically, as the
user fills in the form, before the actual submission. ( it's hooked to
onblur on the input fields )

It should look something like this:
- user changes away from the input field ( onblur )
- javascript takes the name & value of the field, does POST to my
pre_validate action
- the pre_validate action validates this single field and outputs the
validation result in JSON
- the javascript updates the form with validation error messages if
required

( All this would be very handy ( and elegant ) when validating a field
for isUnique, for example. But it also provides a single point of
access to validation rules for scripts wanting to validate form data
pre-submission )

Removing "required" from any of my 3 mandatory fields is not an
option, since i don't want to end up with forged posts passing
validation without these fields. ( ie a user account with no
password.. nasty )

I have done some research here and on the web and found the following
possible solutions:

a, i remove the required flag from my required fields and check for
them beforeSave. Nasty, breaks actual validation, not really what i'm
looking for.

b, i do "->validates()" with only one field "->set()" on the model,
and filter the validation results. Running through all fields when i
expect to have only a single field's data does not seem to be an
elegant solution either.

c, save the validation rules array for the single field i'm validating
for and re-build User->validate with this single field for the
validation-call. This seems to be the most promising way but i still
consider this hacking.

Here comes the question - Is this implemented on the Model? Is there a
way i can execute validation rules for a single field ONLY? If it
isn't ( i believe it isn't ) how would you get around this?

thanks & regards,
Andrew

ps: i'm on 1.3
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: