validate form object and return variable
BSmith001 - September 26, 2008 - 01:07
I'm working on validation of a phone number, I have the form and call the _validate of the string, now I can't pass the updated string back to the form. I tried set_from_update, but wasn't getting it right.
Snippet of form, call_validate, validate. This isn't about passing the call from form->call validate->validate functions, that works, it's about passing the validate info back to the form so that it correctly inserts the formatted phone number into the db
//++++++++++++++++++++++++++++
function contact() {
.
.
.
$form_values['dest'] {
'#type' => 'textfield',
'#value' => dest,
}
.
.
.
}
//+++++++++++++++++++++++++++++
function contact_validate($form_id, $form_values) {
if (!validate_dest($form_values['dest'])) {
form_set_error('dest', t('invalid phone num.'));
}
}
//++++++++++++++++++++++++++++++
function validate_dest($dest) {
$dest = preg_replace('/\D/', "", $dest); $len = strlen($dest);
switch ($len) {
case 10: $dest; return "1" . $dest;
case 11: if ($dest[0] != "1") $dest = "1" . $dest; , $dest); return $dest;
case 12: return ($dest[0] == "1" ? $dest : false);
default: return false;
}
Well, it can't work, as you
Well, it can't work, as you don't take the returned value. In
if (!validate_dest($form_values['dest'])) {form_set_error('dest', t('invalid phone num.'));
}
you simply check for true or false. You could try
if (!validate_dest(&$form_values['dest'])) {
form_set_error('dest', t('invalid phone num.'));
}
}
//++++++++++++++++++++++++++++++
function validate_dest(&$dest) {
$dest = preg_replace('/\D/', "", $dest); $len = strlen($dest);
switch ($len) {
case 10: $dest; $dest = "1" . $dest; return true;
case 11: if ($dest[0] != "1") $dest = "1" . $dest; , $dest); return true;
case 12: return ($dest[0] == "1" ? true : false);
default: return false;
}
the code line for case 11 is still incorrect, but I couldn't figure out, what you've tried to code there.
Give it a try and see, if it works better.
Regards
Werner
TY, I did find the syntax
TY, I did find the syntax error in the case 11 step.
But, you are saying that I can pass the validation back to my form by using:: function validate_dest(&$dest) {, and :: if (!validate_dest(&$form_values['dest'])) {
Does the & in this statement create \ update the dest var? I'm asking so that I don't just get the answer, I understand how to build this function in the future.
Thanks
This is call by reference
There is a general difference between a call by reference and a call by value.
function name (&$var) {...} is a call by reference. By changing the value of $var in the function, you are changing the value of the variable in the calling function (be careful to hand over constants in such a case!!!)
function name ($var) {...} is a call by value (i.e. a copy of the original). Any change in the function doesn't affect the value in the calling routine.
That's all.
Regards
Werner