integer validation for text fields in yii - validation

I had a text field in my form like
$form->textField($model,'test',array('required'=>'true'))
The validation works for required field. Is any way to give validation for an integer like this . I tried Like
$form->textField($model,'test',array('required'=>'true','integer'=>'true'));
But it doesn't work. Is any other way to do it
Thanks in advance

in your model under rules() function add the rule like below
array('test', 'numerical', 'integerOnly'=>true),

This has to be done in the rules. Your code as provided was:
$model = "someString";
$form->textField($model,'test',array('required'=>'true'));
This code itslef will not cause the field to be required, all it will do is add a required attribute with a value of true to the generated HTML, e.g.:
<input name='someString' required='true'>test</input>
That's not going to cause validation to run. Validation will run because of rules defined in the model, and can not be added during the view stage.

We can also use like this -
array('number_value', 'match', 'pattern'=>'/^[0-9]+$/', 'message'=>"{attribute} no. Invalid."),

Related

Laravel 5.4 : Dynamic validation rule

I kind of struggle to find the answer to my question, and my test don't prove to be useful. So maybe someone here would have hit the same issue that I'm facing.
I have inputs with the following kind of patterned name projects-0-1, project-0-2, project-1-0 and so on... These are file inputs so people can upload a document/an image.
So basically, I've been trying to get a validation message that would (ideally) be something like that:
$validator->getMessageBag()->add('project-*-*', 'File is empty!');
OR
$validator->getMessageBag()->add('project-*', 'File is empty!');
I tried a couple of things already and nothing seems to work.
The reason I get to add a custom message is that file is simply not validated if it comes empty to the $request object. So I first need to check if the $request->hasFile and in case it doesn't I want to add the error message.
Things to consider:
inputs can be dynamically added to the form, so I don't know the exact number of file inputs I need to validate beforehand.
even if this should not impact the code and validation, it's worth noticing that everything happens through ajax as I embed the form on another website. Therefore I created endpoints etc...
Any hint ?
Right, coming back here in case someone faces that issue too. I found a "hacky" way to get there and it does the trick for me.
As each input file is dynamically added to the DOM, I add an extra hidden input that holds the name of the file input as a value.
Then in my controller I do smth like that:
public function createValuesKeyArray ($preset)
{
$regexPattern = '/^'. $preset .'-[0-9]*$/';
$customPresets = preg_grep($regexPattern, array_keys(Input::all()));
$keys = [];
foreach ($customPresets as $customPreset) {
array_push($keys, $customPreset);
}
return $keys;
}
// This allows me to get all hidden input names in an array in order to get its value from the $request
$hiddenInputs = $this->createValuesKeyArray('hidden-project-name');
Once I get this array, I can do stuff like that and dinamycally add my set of rules for the input files present in the DOM:
foreach($hiddenInputs as $hiddenInput){
$globalRules[$request[$hiddenInput]] = 'required';
}
Not sure if this the right way to get there, but it does the job for me and I don't find that code horrible. I'll stick with it until I find a better way.

Codeigniter form validation, custom check doesn't work if the field is not required

Gah.. I have spent way to long on this, but I believe I have found the problem.
Essentially I have a hidden field which is populated when a user clicks on an image.
It is required that the user has clicked the image but I do not want the generic form error message for a 'required' check with the CI form validation class.
As such I quickly made a image_required function in my extended form validation class, and set a rule such that this rule was applied to the hidden field.
function image_required($str)
{
$CI =& get_instance();
$CI->form_validation->set_message('image_required','Please click the image above.');
if($str != '')
{
return TRUE;
}
else
{
return FALSE;
}
}
If the hidden field was blank no error was being called.
I am led to believe now that this is because CI says this field is empty yet it is not 'required', therefore we will ignore all the other validation rules for the field. Is this correct?
If so how can i go about requiring this field be set but having a custom error message?
bangs head
Thanks
If you look at the source code (v2.1.3) for the '_execute' routine (system/libraries/Form_validation.php) you will see on line 486
// If the field is blank, but NOT required, no further tests are necessary
So you are correct, it needs to be required and then it will process your rule.
In order to fix it so you can have a non-required blank field that still processes rules, you should override the '_execute' method by creating a file called 'MY_Form_validation.php' in the application/libraries folder (I think, you might need to check exactly how you extend an existing library) and then copy the '_execute' method and alter the code to continue on a non-required but blank entry.
I do love CI, but I have to say this does not allow the flexibility required. It is perfectly reasonable to have a field that cannot be empty, but is NOT required. As in, you wouldn't enforce "user MUST enter a value", but they cannot submit a blank. I think someone got confused between EMPTY and REQUIRED.
1) REQUIRED: User MUST put a value in the field and it cannot be empty (i.e. '')
2) EMPTY: User does not HAVE to enter a value, BUT, if they do, it's cannot be empty. This not the same as REQUIRED... Looks like I'll be using a callback again.
REQUIRED incorporates two logical steps (1->Must enter a value, and 2->Cannot be empty) these two steps should be separated logically to allow either / or.
In constraint terms it would be either, REQUIRED, NOT NULL. Or NOT REQUIRED, NOT NULL.

Yii : form values retention for CHtml::checkBoxList on form validaton

I am using CHtml::checkBoxList for my form. For some reason I cannot use CHtml:activeCheckBoxList or CActiveForm::checkBoxList. Everything works fine only problem is that I loose checkbox values on form validation error. What could be the easiest way to fix this ?
If you're making a form, you probably want to use CActiveForm's checkboxlist, which is a form-specific wrapper of CHtml::activeCheckBoxList) instead. Something like
echo $form->checkBoxList(
$model,
'condiments',
array(
'ketchup'=>'Ketchup',
'mustard'=>'Mustard',
'relish'=>'Relish',
'onions'=>'Onions'
)
);
should give you a persistent check box list of hot dog condiments, for example.

adding attributes to form_open_multipart

I was wondering how could we add attributes to file_upload in codeigniter
right now I am using form_open_multipart('controller');
but I want to add an id attribute to it.
Any help appreciated thanks!
From the User Guide:
form_open_multipart()
This function is absolutely identical
to the form_open() tag above except
that it adds a multipart attribute,
which is necessary if you would like
to use the form to upload files with.
So, you would use it in the same way you use form_open(). Example:
form_open_multipart('controller', 'id="my_id"');
Or:
form_open_multipart('controller', array('id' => 'my_id'));

Silverlight 4: Localization of built-in data annotation validation exceptions

I would like use data annotations to handle validation in my Silverlight app. The built-in validation attributes (primarily StringLength and Required) are great, and make life very easy. However, they seem to have one critical flaw. If my locale is set to fr-CA, for example, the validation exceptions are still in English - 'The Name field is required', 'The field Name must be a string with a maximum length of 20', etc.
This is a major problem. It means that if I want localized error messages for the built-in validation attributes, I have to manually add ErrorMessage/ErrorMessageResourceType to every validation attribute on every validatable property in my business layer, and manually add translated strings for every error message.
So... am I missing something here? Is there a way to automatically have the built-in validation attributes localized? Or some other easier way of doing this? Or am I just completely out of luck, and stuck with the manual route?
Any comments or thoughts would be appreciated.
Ok, I got around this by simply subclassing the built-in validation attributes. Problem solved!
internal class LocalizedStringLengthAttribute : StringLengthAttribute
{
public LocalizedStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, LanguageResources.Resource.Error_StringLength, name, MaximumLength);
}
}

Resources