Struggling to understand why my validator chain is showing the incorrect message for the value I type in.
Currently my model's code is making the incorrect message appear when I type in non-identical passwords instead of just the expected 3rd message ('Please retype password between 8-25 alphanumeric characters and matching the first password' when expecting 'Retyped password must match first.') when i type in mismatched passwords of 8 -25 characters long.
$password2 is the one giving issues
Also unsure if the indentical validator is working due to this problem.
Zend Framework version 1.11
Specific code chunk related to above
$password2 = new Zend_Form_Element_Password('password2');
$password2->setAttrib('size', 25);
$password2->setRequired(true);
$validatorChain2 = new Zend_Validate();
$validatorChain2->addValidator(new Zend_Validate_StringLength(array('min' => 8,'max' => 25)), true);
$validatorChain2->addValidator(new Zend_Validate_Alnum(false), true);
$validatorChain2->addValidator(new Zend_Validate_Identical('password1'), true);
$password2->addValidator($validatorChain2);
$password2->addErrorMessage('Please retype password between 8-25 alphanumeric characters and matching the first password');
$password2->addErrorMessage('Passwords can only be alphanumeric characters.');
$password2->addErrorMessage('Retyped password must match first.');
Full model code listing
class Application_Model_RegisterNewAccount extends Zend_Form
{
public function __construct($options = null)
{
// TODO: The errors are been grouped together at the top of the page now but the original error messages below each field need to be removed
parent::__construct($options);
$this->setName('newaccountregistration');
$this->setMethod('post');
$this->setAction($options['action']); // Variable action passed via parameter array for argument 'action'
$email = new Zend_Form_Element_Text('email'); // Create form text field
$email->setAttrib('size', 75); // Set for, element max size/length
$email->setRequired(true); // Make this field a required item
$validator_email = new Zend_Validate_EmailAddress();
$email->addValidator($validator_email); // Set validator type and minimum and maximum size required
$email->addErrorMessage('Please provide a valid email address');
$firstname = new Zend_Form_Element_Text('firstname');
$firstname->setAttrib('size', 35);
$firstname->setRequired(true);
$validator_firstname = new Zend_Validate_StringLength(array(1,35));
$firstname->addValidator($validator_firstname);
$firstname->addErrorMessage('Please provide your first name between 1-35 characters');
$surname = new Zend_Form_Element_Text('surname');
$surname->setAttrib('size', 35);
$surname->setRequired(true);
$validator_surname = new Zend_Validate_StringLength(array(1,35));
$surname->addValidator($validator_surname);
$surname->addErrorMessage('Please provide your first name between 1-35 characters');
$password1 = new Zend_Form_Element_Password('password1');
$password1->setAttrib('size', 25);
$password1->setRequired(true);
$validatorChain1 = new Zend_Validate();
$validatorChain1->addValidator(new Zend_Validate_StringLength(array('min' => 8,'max' => 25)), true);
$validatorChain1->addValidator(new Zend_Validate_Alnum(false), true);
$password1->addValidator($validatorChain1);
$password1->addErrorMessage('Please provide a password between 8-25 alphanumeric characters');
$password1->addErrorMessage('Passwords can only be alphanumeric characters.');
$password2 = new Zend_Form_Element_Password('password2');
$password2->setAttrib('size', 25);
$password2->setRequired(true);
$validatorChain2 = new Zend_Validate();
$validatorChain2->addValidator(new Zend_Validate_StringLength(array('min' => 8,'max' => 25)), true);
$validatorChain2->addValidator(new Zend_Validate_Alnum(false), true);
$validatorChain2->addValidator(new Zend_Validate_Identical('password1'), true);
$password2->addValidator($validatorChain2);
$password2->addErrorMessage('Please retype password between 8-25 alphanumeric characters and matching the first password');
$password2->addErrorMessage('Passwords can only be alphanumeric characters.');
$password2->addErrorMessage('Retyped password must match first.');
$submit = new Zend_Form_Element_Submit('submit'); // Added submit button
$submit->setLabel('Register');
$submit->removeDecorator('DtDdWrapper'); // Remove the default DD div wrapper
$this->setDecorators( array( array('ViewScript',
array('viewScript' => '_register.phtml')))); // The form html page
$this->addElements(array($email, $firstname, $surname, $password1, $password2, $submit)); // Add all the form elements
}
}
You should instantiate it like this...
$validatorChain2->addValidator(new Zend_Validate_Identical(array('token' => 'password1', 'messages' => ....)), true);
Related
My project requires me to retrieve inbound & outbound mails, retrieve the recipient emails, cc emails, sender email, store the retrieved emails in the database, do some computation, and update or create a row in google sheets.
My steps to doing the task:
In zapier, I have create zaps that triggers when receiving, and sending mails.
In my laravel, I have a function that receives and stores the data in the database from zapier when the receive/sent zap triggers.
After storing all the data, the function will then return the email, email domains of the inserted data, which will then be passed to the computation function.
I also have a zap that updates the google sheet. (My api -> Webhooks by Zapier -> Google Sheet)
After the computation, the computed data, in a form of multidimensional array, loop through it, and call the Update sheet webhook endpoint in each iteration.
A sample code, let's do example for sending mails:
// Controller
public function sent(Request $request)
{
$recipients = explode(",", $request->recipients); // Need to explode since the recipients is being received as comma delimited string.
$ccs = explode(",", $request->ccs); // Need to explode since the cc emails is being received as comma delimited string.
ProcessMail::dispatch($recipients, $ccs);
}
// Service class responsible for doing the logic
public function processSent($recipients, $ccs)
{
$new_recipients = [];
$new_ccs = [];
foreach ($recipients as $recipient) {
$domain = explode('#', $recipient)[1];
$recipientModel = tap(Mail::updateOrCreate(
['email' => $recipient, 'domain' => $domain],
))->increment('count_column');
$new_recipients[] = [
'email' => $recipient,
'domain' => $domain,
'count_column' => $recipientModel->count_column,
];
}
// Same process for the cc emails
return array_merge($new_recipients, $new_ccs);
}
// ProcessMail Job
$recipients_and_ccs = $service->processSent($recipients, $ccs);
Http::pool(function (Pool $pool) use ($service, $recipients_and_ccs ) {
foreach ($recipients_and_ccs as $key => $rec_cc) {
$addtl_rows = $service->getAddtlRows($rec_cc['email'], $rec_cc['domain']);
// The purpose of this to append 5 additional key value pair in the array.
for ($i = 0; $i < 5; $i++) {
$rec_cc["addt_row_{$i}"] = isset($addt_rows[$i]) ? 'this' : 'that';
}
$pool->as("pool-{$key}")->withBody(json_encode($rec_cc), 'json')->post('ZAPIER_ENDPOINT');
return $pool;
}
});
Now, when I send a mail to 50 recipients, some of the task in the zap will stop with error saying: The app returned "Resource has been exhausted (e.g. check quota)."..
One solution that I can think of is to chunk the $recipients_and_ccs by desirable amount of rows, say 10 records per chunk.
But before I start with my solution. It would be really great to hear some more pro/optimized solution.
I have few users with no email and password, and I would like to update users by adding email from freemail column, and setup password from random string.
This is my sample code:
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->email = $users->freemail;
$updateUser->remember_token = str_random(10);
$updateUser->motdepasse = $motdepasse;
$updateUser->password = bcrypt($motdepasse);
$updateUser->isfree = 0;
$updateUser->save();
}
The problem is that when I try to connect with email($users->freemail) and password($motdepasse), which is not encrypted random string, I get error that:
my credential is not valid
what did I miss ?
You can use update() to update rows. So your code must be
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->update([
'email'=>$users->freemail,
'remember_token'=>str_random(10),
'motdepasse'=>$motdepasse,
'password'=>bcrypt($motdepasse),
'isfree'=>0,
]);
}
Heres the problem
I want to require a field (litters_per_year) only if another field that is a checkbox is checked. When I do this, cake is trying to force me to put a value into the field and I don't know why. I have tried setting required & allowEmpty to false & true respectively, but then my custom rule does not run.
Heres the code
NOTE: The details of the following code aren't that important - they are here to provide a scenario.
I have the following code in my VIEW which works fine:
echo $this->Form->input('litters_per_year', array(
'label' => 'Litters per year (average)'
));
I have the following code in my MODEL's public $validate:
'litters_per_year' => array(
'isNeeded' => array(
'rule' => array('isNeeded', 'litters_per_year'),
'message' => 'Please enter the litters per year average'
)
)
which is calling the custom validation method
public function isNeeded($field) {
// Check if a checkbox is checked right here
// Assume it is not... return false
return false;
}
It returns false for simplicity to solve this issue.
Let's assume that the checkbox field is named 'the_checkbox'.
At the moment your field should always fail validation, since you return false from isNeeded.
To make it work as you expect, do something like this:
(Note: replace 'ModelName' with your model name)
public function isNeeded($field) {
if ($this->data['ModelName']['the_checkbox']) {
// Checkbox is checked, so we have to require litters per year
if (empty($field)) {
// They have checked the box but have NOT entered litters_per_year
// so we have a problem. NOT VALID!
return false;
} else {
// They have checked the box, and entered a litters_per_year
// value, so all good! Everything is valid!
return true;
}
} else {
// Checkbox is not checked, so we don't care what
// the field contains - it is always valid.
return true;
}
}
Or, without the needless verbosity, this should work:
public function isNeeded($field) {
if ($this->data['ModelName']['the_checkbox']) {
return $field;
} else {
return true;
}
}
In this example, if the checkbox is checked, validation will pass if $field is truthy, and fail if it is falsey.
I'm using a model with DataType.EmailAddress. I would like to modify the address link in the run time, however it already has email link automatically that prevents my modification.
#{
var subject = "";
if (Model.Name.Length > 30)
{
subject = Model.Name.Substring(0, 30) + "...";
}
else
{
subject = Model.Name;
}
}
model => model.email
But I got
<a href="mailto:emailaddress">emailaddress</a>
instead of
emailaddress
Why the email address is converted into link form automatically? And how to stop it? I would like to keep the datatype to use validation though.
You're trying to print the value of the property: #model.Email.
DisplayFor is not what you want.
Also, you need to URL-encode the subject parameter, including the space after Re:.
i am trying to do Recurring Payments on my site. but i gettin a problem here.
its is giving ack=Fail
[TIMESTAMP] => 2012-06-21T04:36:01Z
[CORRELATIONID] => fe0a920b9dee5
[ACK] => Failure
[VERSION] => 65.1
[BUILD] => 3067390
[L_ERRORCODE0] => 11549
[L_SHORTMESSAGE0] => Start Date is required
[L_LONGMESSAGE0] => Subscription start date is required
[L_SEVERITYCODE0] => Error
while my code for the reoccuring which i am passing is
function DoRecuringPayment($paymentInfo=array()){
/**
* Get required parameters from the web form for the request
*/
$paymentType =urlencode('Sale');
$firstName =urlencode($paymentInfo['Member']['first_name']);
$lastName =urlencode($paymentInfo['Member']['last_name']);
$creditCardType =urlencode($paymentInfo['CreditCard']['credit_type']);
$creditCardNumber = urlencode($paymentInfo['CreditCard']['card_number']);
$expDateMonth =urlencode($paymentInfo['CreditCard']['expiration_month']);
$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);
$expDateYear =urlencode($paymentInfo['CreditCard']['expiration_year']);
$cvv2Number = urlencode($paymentInfo['CreditCard']['cv_code']);
$address1 = urlencode($paymentInfo['Member']['billing_address']);
$address2 = urlencode($paymentInfo['Member']['billing_address2']);
$country = urlencode($paymentInfo['Member']['billing_country']);
$city = urlencode($paymentInfo['Member']['billing_city']);
$state =urlencode($paymentInfo['Member']['billing_state']);
$zip = urlencode($paymentInfo['Member']['billing_zip']);
$bperiod=urlencode( $paymentInfo['Bill']['month']); ;
$bfrequency=urlencode($paymentInfo['bill']['frequency']);
$amount = urlencode($paymentInfo['Order']['theTotal']);
$currencyCode="USD";
$time22= date('Y-m-d',time());
$startdate=urlencode(date('Y-m-d',time()));
$paymentType=urlencode('Sale');
$ip=$_SERVER['REMOTE_ADDR'];
/* Construct the request string that will be sent to PayPal.
The variable $nvpstr contains all the variables and is a
name value pair string with & as a delimiter */
$nvpstr="&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&CITY=$city&STATE=$state".
"&ZIP=$zip&COUNTRYCODE=US&CURRENCYCODE=$currencyCode&PROFILESTARTDATE=$startdate&BILLINGPERIOD=$bperiod&BILLINGFREQUENCY=$bfrequency";
/* Make the API call to PayPal, using API signature.
The API response is stored in an associative array called $resArray */
$resArray=$this->hash_call("CreateRecurringPaymentsProfile",$nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
return $resArray;
//Contains 'TRANSACTIONID,AMT,AVSCODE,CVV2MATCH, Or Error Codes'
}
I geting the error Subscription start date is required.