Luis Majano Forums Notification: Post to Form Validation

Title: RE: Form Validation
Thread: Form Validation
Forum: Need Help?
Conference: ColdBox
User: oscararevalo

Luis,
The idea of an onPopulateError is good but i think it has a problem. It
assumes that the bean will (or could) be populated by some external mechanism,
like coldbox, increasing the coupling between the bean (an abstract and
implementation agnostic construct) and coldbox (a concrete implementation)
Other alternatives could be to use something similar to the validate method you
proposed before, but modify it to accept a struct with the values to be
populated, and this method should return perhaps an array of user-friendly error
messages. This way the handler is only limited to pass along the data received
from the Form into this validation method, if nothing is returned then proceeds
to setup the bean, otherwise it sends the returned collection of errors to the
user, knowing that the messages are (or are expected to be) user friendly.
Something like this:

[code]
// get your bean
oAddress =
CreateObject("component","model.address");

// build a struct with the form
data
stData = structNew();
stData.address = getValue("address");
stData.city
= getValue("city");
....

// validate the data
aErrors =
oAddress.validate(stData);

// if no errors then do your thing
if(arrayLen(aErrors) eq 0) {
getPlugin("beanfactory").populatebean(oAddress);
    oAddress.save()
} else {
// put all errors in aErrors into a message
}
[/code]

Now, to get a bit
more funky, we could detach this behavior into some sort of "beanValidator"
object, that is related to the bean; so the bean remains as just a container of
data. Let's say you could have a productBean.cfc and a productBeanValidator.cfc
which its sole responsibility would be to authorize the population of the bean.
So, since I know you are always eager to add more stuff into coldbox :slight_smile: , you
could allow for this on the mechanism used to populate the bean, for example
having an optional parameter to point to the appropriate validator object (via
passing the actual reference to the object, or may by passing the path to the
cfc), then as long as this validator object adheres to a given contract, coldbox
would call this object before populating the bean, if the validation fails, the
call to populateBean will return the array (or query or whatever) with the
messages.

Something along the lines of:

[code]
oAddress =
CreateObject("component","model.address");
oAddressValidator =
CreateObject("component","model.addressValidator");

aErrors =
getPlugin("beanfactory").populatebean(oAddress, oAddressValidator);
if(arrayLen(aErrors) eq 0) {
    oAddress.save()
} else {
  // put all errors
in aErrors into a message
}

[/code]

http://www.luismajano.com/forums/index.cfm?event=ehMessages.dspMessages&threadid=099E0187-123F-6116-421FA3B9B2F4006A