I am creating a module to validate club card number. There is one additional field added in the customer registration form which validates the number entered by user.
I have called the observer on controller_action_predispatch_customer_account_createpost
event.
My XML code is a below:
<events>
<controller_action_predispatch_customer_account_createpost>
<observers>
<tescoclubcard_validate>
<type>singleton</type>
<class>tescoclubcard/observer</class>
<method>validateTescoCardNumber</method>
</tescoclubcard_validate>
</observers>
</controller_action_predispatch_customer_account_createpost>
</events>
In Observer.php file I have performed all validation. I am throwing the exception when the card number is not valid. The function code is as below:
public function validateTescoCardNumber($observer = null, $number = null){
$event = $observer->getEvent();
$controllerAction = $event->getControllerAction();
$params = $controllerAction->getRequest()->getParams();
// Retrives card number from the controller action.
$tescoClubCardNumber = $params['tescoclubcard_number'];
if($tescoClubCardNumber != NULL){
$tescoClubCardStatus = $this->checkCard($tescoClubCardNumber);
}
try{
if($tescoClubCardStatus == "N"){
Mage::throwException('Invalid Tesco Club Card Number');
}
}catch(Mage_Core_Exception $e){
$session = Mage::getSingleton('customer/session');
$session->addError($e->getMessage());
}
}
Here, the exception is thrown successfully and the error message is printed out properly but still the account is created which ideally shouldn't have been done.
I want to stop the customer registration and redirect customer back to create account page with the error message displayed as it happens for normal customer registration invalid fields.
Can anyone please provide an insight on how can I work this out.
Best Answer
The right way to do this is creating a customer attribute for the club cart number with a custom attribute model. There you just have to implement a
validateValue()
method and Magento will take care of validation, error messages and preventing registration.Have a look at
Mage_Customer_Model_Attribute_Data_Postcode
to see how it works.Example
To update the existing attribute, use this code in a setup script: