I have a form with a URL field. The default value for this field is: http://. But the field is not required. The user can skip it and submit the form. It shouldn't return an error because it's not required and because they didn't enter a URL. But right now it does, because of the http://.
I heard I can use beforeValidate() to check if it's http://, and then clear the URL field, allowing me to skip the error message.
But I don't know how to use beforeValidate(). I searched Google, but I did not find any working examples. Where do I place the code for beforeValidate()? Is it a function? How do I access the submitted form data from there?
Thanks.
Yes, beforeValidate() is a function of the model. So every model has it. How you should use it:
class YourModel extends AppModel {
function beforeValidate(){
if($this->data['YourModel']['url_field'] == 'http://'){
unset($this->data['YourModel']['url_field']);
}
return true; //this is required, otherwise validation will always fail
}
}
instead of hard coding http:// into the form, add proper validation for urls and use the following to allow blanks
'allowEmpty' => true
Related
I have a question about enabling the is_unique() rule for form validation in CodeIgniter.
In another explanation (link), they don't include the model query builder for standard usage of is_unique()
I need to use the rule is_unique(table.field) for my id field.
What should I do for making this function work on my model file to initiate table.field from my database? Because at documentation, I didn't see an explanation for enabling the is_unique rule.
My current code is still use matching data manually, but I need to know how to use this rules
$this->form_validation->set_rules('siteid', 'Site ID', 'trim|required|max_length[100]|is_unique[site_tower.site_id_tlp]');
I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.
With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.
For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.
How do we fix this? We run our own callback in which we specify the logic.
You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
This will then look for a method in your controller called 'username_check'
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.
more information can be found on Ci3 documentation.
LINK
Use CTRL + F and search for callback or is_unique
You might have missed this?
$this->load->library('database');
works instantly after adding database lib.
I need to validate that a form input is numeric in CakePHP 1.3. However, the input is not a property of the model, so I don't think I should try to set the validation for it in the model. Instead, some calculations are done on that input and the results are used in the resulting model object. How can I validate this in the view/controller? That is, check that what the user input was numeric and show a validation error message if not before passing it through the calculations? Thanks!
There's nothing wrong with defining model validation rules for non-existing / calculated fields, but you can also use the Validation class which might be cleaner. See 1 and 2.
If you use jquery at least you don't have to do a full page reload to check. Especially if it's only for one value. Just another option, see if it helps!
if($('#Field').val() != "")
{
if(!($.isNumeric($('#Field').val())) {
alert('value must be numeric');
}
}
Hi I'm trying to make my own Form validator just like the authenticate method in the LoginForm that is generated on the default configs.
public function rules()
{
return array(
// username and password are required
array('mnemonic, target_reg, source_reg', 'required'),
// rememberMe needs to be a boolean
array('target_reg_indirection, source_reg_indirection', 'boolean'),
array('mnemonic','foo'),
);
}
and here is the validator method:
public function foo($attribute,$params){
$this->addError('mnemonic', 'there was an error, you foo!');
}
it just doesn't work for me... notice how I added a rule that should not-work everytime. I just made it so I could see how it worked. But I never get to see the error message in my view. The default validators (like the one that checks for required fields) work.
Any ideas?
Because not all validators map to a client-side validator.
IN addition to that, I've created the code to handle ajax form validation and I've enabled ajaxValidation in my CActiveForm.
So now all works great. The validator I've created is working via ajax validation.
I had the same problem, in my case wasn't to enabled ajaxValidation, but the "safe" validator and a mix of other things.
Here I post some reading that helped me to solve the problem. Hope this will help others with the same problem.
I read a little bit about "safe" validator. (http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/)
I Understand the difference between AjaxValidation and ClientValidation. (http://www.yiiframework.com/doc/api/1.1/CActiveForm)
I created my own validator class. (search "custom validation yii" on google).
I'm developing with Codeigniter and working on password reset using a similar model to Amazon: The user clicks on a link that I email and this leads into the controller that launches the appropriate view. However I need to attach some tokens to the end of the uri for security reasons. Where do I intercept the uri within Codeigniter so as to remove the tokens? I would appreciate a code snippet that demonstrates this.
Many thanks in advance.
You can send an URL like www.yousite.com/index.php/password/reset/116wef4wef4325w6e4
In your controller password.php you have:
class Password extends CI_Controller {
function reset($token)
{
if(isset($token) AND $token != '')
{
$retrived_token = $token; //it's automatically passed by CI to this method.
//It would output 116wef4wef4325w6e4
//you may do some validation of it through a model here.
//ex. if($this->mymodel->validate_token($retrieved_token)
//{ do something } else { }
}
}
}
You didnt provide any info on how your app is structured, so I just guessed you might have a controller just for dealing with passwords. If it's not the case, you can have a 'password' method inside the parent controller, which in turn takes 2 parameters, in this case 'reset' and the 'token'. Or you could use a custom route maybe. If you provide this informations I might help updating my code suggestion.
I would like to validate an embedded form field before it gets saved in the database. Currently it will save an empty value into the database if the form field is empty. I'm allowing empty fields, but I want nothing inserted if the form field is empty.
Also quick question, how to alter field values before validating/saving an embedded form field?
$this->form->getObject works in the action, but $this->embeddedForm->getObject says object not found
I found a really easy solution. The solution is to override your Form's model class save() method manually.
class SomeUserClass extends myUser {
public function save(Doctrine_Connection $conn = null)
{
$this->setFirstName(trim($this->getFirstName()));
if($this->getFirstName())
{
return parent::save();
}else
{
return null;
}
}
}
In this example, I'm checking if the firstname field is blank. If its not, then save the form. If its empty, then we don't call save on the form.
I haven't been able to get the validators to work properly, and this is an equally clean solution.
Symfony gives you a bunch of hooks into the form/object saving process.
You can overwrite the blank values with null pre/post validation using by overriding the the doSave() or processValues() functions of the form.
You can read more about it here: http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms#chapter_06_saving_object_forms