Validation Parameter Get Method in fuelphp - php

i have a problem when i want to validate using GET Method in fuelphp
i'm looking up in this documentation
// run validation on just post
if ($val->run())
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
that's code only validate if the method is Post or default post.
how to validate method get?

To run the validation against an array:
if ($val->run( array( $validation_rule => $value_to_validate) ))
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
Example:
$val = Validation::factory();
$val->add('email')->add_rule('valid_email');
if ($val->run( array('email'=>$email) ))
{
// $email is valid
}
else
{
// $email is not valid
}

Related

Check if POST data was sent to page

I am trying to check if POST data has been sent to a page. A quick Google search turned up nothing.
if(postdataisSent)
{
//do this
}
else
$items = Gamefarm::where('roost_hen', '=', 1)->paginate(6);
return View::make('gamefarms/index',compact('items'));
You can use if ( Input::has('parameter') ) to check for the existence of a certain parameter in the POST, or you can pass a default into the function, and then test if it's there.
$parameter = Input::get('parameter', false);
if ($parameter)
{
// do something with the data
}
else
{
// it's not present in the POST
}
To check for the presence of any data at all:
$data = Input::all();
if (count($data) > 0)
{
// there is data in the POST
}
else
{
// there is no data in the POST
}
Note - You can access the data from any HTTP verb (GET, POST etc) using the same Input::get('data')

Validate another field if file field is not empty

I'm trying to validate a field if a file fields is not empty. So if someone is trying to upload a file, I need to validate another field to make sure they selected what they are uploading, however I don't know how to check to see, or run a rule only if the field is not empty.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('full_name, gender_id','required'),
array('video', 'file', 'types'=>'mp4', 'allowEmpty' => true),
array('audio', 'file', 'types'=>'mp3', 'allowEmpty' => true),
array('video','validateVideoType'),
);
}
public function validateVideoType() {
print_r($this->video);
Yii::app()->end();
}
So this->video is always empty whether I just uploaded something or not. How do I check to see if that variable is set?
Custom validation function must be defined properly. It has two parameters always $attribute & $params.
public function validateVideoType($attribute, $params) {
print_r($this->video);
Yii::app()->end();
}
Now in this you should write your custom way to validate.
I am sure that would work fine.
You can check it with jQuery/javascript, where 'new_document' is the name of the input file field.
if ($("#new_document").val() != "" || $("#new_document").val().length != 0) {
//File was chosen, validate requirements
//Get the extension
var ext = $("#new_document").val().split('.').pop().toLowerCase();
var errortxt = '';
if ($.inArray(ext, ['doc','docx','txt','rtf','pdf']) == -1) {
errortxt = 'Invalid File Type';
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html(errortxt);
return false;
}
//Check to see if the size is too big
var iSize = ($("#new_document")[0].files[0].size / 1024);
if (iSize / 1024 > 5) {
errortxt = 'Document size too big. Max 5MB.';
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html(errortxt);
return false
}
} else {
//No photo chosen
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html("Please choose a document.");
return false;
}
This code is obviously not perfect for your needs but may have the requirements to piece together what you need.

Codeigniter use form validation for variable

I've read somewhere that is possible to use Codeigniter's Form Validation also for my own variables and not only for form's inputs.
For example I'd like to validate a url to say if it is valid but not retrieving it using POST or GET from a form.
Do you know how or have a link?
What you are looking for are the callbacks of the Form Validation Class in CodeIgniter - read the user guide for an in-depth explanation.
For PHP5 above version,you can do this
function validdate_urls($str) {
if(!filter_var($str, FILTER_VALIDATE_URL))
{
$this->validation->set_message('validate_urls', 'URL Invalid');
return 0;
}else {
return TRUE;
}
}
And call it in your validation rules :-
$rules['link'] = "callback_validate_urls";
Yes you can via set_data() method, Here you go.
$this->form_validation->set_data(array(
'cartId' => $cartId
));
$this->form_validation->set_rules('cartId', 'Card ID', 'trim|required|is_natural_no_zero');
if ($this->form_validation->run() == FALSE) {
echo 'Invalid: ' . validation_errors();
} else {
echo 'Valid';
}

How to submit a form in Zend?

I have following action to display a form
public function showformAction() {
$this->view->form = new Form_MyForm();
$this->view->form->setAction( 'submitform' );
}
above action shows a form successfully with only one textarea and submit button.
And I am using following action to submit above form:
public function submitformAction() {
$form = new Form_MyForm();
$request = $this->getRequest();
if ( $request->isPost() ) {
$values = $form->getValues();
print_r($values);die();
} else {
echo 'Invalid Form';
}
}
Above action is showing following output:
Array ( [myfield] => )
It means it is not posting values correctly and always shows empty array or I am not getting posted values correctly. How to post values to submitformAction().
Thanks
I think you must use the isValid() before accessing the values of a submitted form, because it's right there that the values are checked and valorized
public function submitformAction() {
$form = new Form_MyForm();
$request = $this->getRequest();
if ( $request->isPost() ) {
if ($form->isValid( $request->getPost() )) {
$values = $form->getValues();
print_r($values);die();
}
} else {
echo 'Invalid Form';
}
}
In complement to #VAShhh response. With some more details:
You need to do two things, populate your form fields with the POSTed data and applying security filters and validators to that data. Zend_Form provides one simple function which perform both, it's isValid($data).
So you should:
build your form
test you are in a POST request
populate & filter & validate this data
either handle the fact in can be invalid and re-show the form wich is now
decorated with Errors OR retrieve valid data from the form
So you should get:
function submitformAction() {
$form = new Form_MyForm();
$request = $this->getRequest();
if ( $request->isPost() ) {
if (!$form->isValid($request->getPost())) {
$this->view->form = $form;
// here maybe you could connect to the same view script as your first action
// another solution is to use only one action for showform & submitform actions
// and detect the fact it's not a post to do the showform part
} else {
// values are secure if filters are on each form element
// and they are valid if all validators are set
$securizedvalues = $form->getValues();
// temporary debug
print_r($securizedvalues);die();
// here the nice thing to do at the end, after the job is quite
// certainly a REDIRECT with a code 303 (Redirect after POSt)
$redirector = $this->_helper->getHelper('Redirector');
$redirector->setCode(303)
->setExit(true)
->setGotoSimple('newaction','acontroller','amodule');
$redirector->redirectAndExit();
} else {
throw new Zend_Exception('Invalid Method');
}
}
And as said in the code re-showing the form you shoudl really try to use the same function for both showing and handling POST as a lot of steps are really the same:
building the form
showing it in the view in case of errors
By detecting the request is a POST you can detect you are in the POST handling case.

Cant load Validation Rules from both config file and using set_rules method

Is there any way to load validation rules from both : config file and using set rules method ?
Without modifying CodeIgniter's Form Validation class (CI_Form_validation), there is no way to load validation rules from a config file AND using the set rules method. As the form validation code currently operates, config file rules are only checked if no rules have been otherwise defined
You can extend the form validation class and get this to work, however, relatively simply. Create a file called MY_Form_validation.php and put it in the application/core/ directory.
class MY_Form_validation extends CI_Form_validation {
// You only need to change the run() method, so we'll define a (modified) version.
// This will override the existing run() method so that it uses rules set from
// set_rules() AND from the config file.
function run($group = '')
{
if (count($_POST) == 0)
{
return FALSE;
}
// If there are any configuration rules defined, go ahead and use them
if (count($this->_config_rules) != 0)
{
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri]))
{
$this->set_rules($this->_config_rules[$uri]);
}
else
{
$this->set_rules($this->_config_rules);
}
}
// Load the language file containing error messages
$this->CI->lang->load('form_validation');
// Cycle through the rules for each field, match the
// corresponding $_POST item and test for errors
foreach ($this->_field_data as $field => $row)
{
// Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
// Depending on whether the field name is an array or a string will determine where we get it from.
if ($row['is_array'] == TRUE)
{
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
}
else
{
if (isset($_POST[$field]) AND $_POST[$field] != "")
{
$this->_field_data[$field]['postdata'] = $_POST[$field];
}
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
}
// Did we end up with any errors?
$total_errors = count($this->_error_array);
if ($total_errors > 0)
{
$this->_safe_form_data = TRUE;
}
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
// No errors, validation passes!
if ($total_errors == 0)
{
return TRUE;
}
// Validation fails
return FALSE;
}
Note, I haven't tested this on a CodeIgniter installation. But it should work. Also note, this will prioritize config file rules over rules defined using the set_rules() method.

Categories