I'm trying to validate a form in the actual form itself, but it doesn't get validated at all. If I type "someemail&*!([]#gmail.com", it doesn't really give a crap and moves on.
Form:
class RecoverPasswordForm extends Form {
public function __construct($options = null) {
parent::__construct("RecoverPassword");
$username = new Element("username");
$username->setLabel("Email");
$username->setAttributes(
array('filters' => array(
array('name' => 'StringTrim'),
array('name' => 'StripTags')),
'validators' => array(
array(
'name' => 'Regex',
'options' => array(
'pattern' => '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/',
'messages' => array(
Regex::NOT_MATCH => 'The email your provided has invalid characters.',
),
),
'break_chain_on_failure' => true
),
array(
'name' => 'EmailAddress',
'options' => array(
'messages' => array(
EmailAddress::INVALID_FORMAT => "Email address is invalid",
EmailAddress::INVALID => "",
EmailAddress::INVALID_LOCAL_PART => "",
EmailAddress::INVALID_HOSTNAME => "",
EmailAddress::INVALID_SEGMENT => "",
EmailAddress::DOT_ATOM => "",
EmailAddress::INVALID_MX_RECORD => "",
),
),
),
),
'label' => 'Email'));
$this->add(array(
$username,
));
}
}
How I'm getting (or trying to get) the filters and validators in the controller:
public function recoverPasswordAction() {
$this->cache = new Container("cache");
$request = $this->getRequest();
$form = new RecoverPasswordForm();
// $form->get("submit")->setValue("Send mail");
$this->view->form = $form;
if ($request->isPost()) {
$user = new User();
$form->getInputFilter()->getValues();
$form->setInputFilter($form->getInputFilter());
$data = $request->getPost();
$form->setData($data);
$username = $data['username'];
$userData = $this->getServiceLocator()->get("UserTable")->fetchList("`username` LIKE '$username'");
if (!count($userData) > 0) {
$this->cache->error = "A user with this email does not exist, plese try again.";
}
if ($form->isValid()) {
foreach ($userData as $user) {
$user->sendMail(6);
$this->cache->success = "A message has been send to this email, containing your password.";
}
}
}
return $this->view;
}
Try like this...
$request = $this->getRequest();
$form = new Form();
if($request->isPost()) {
if($form->isValid($reguest->getPost())) {
$values = $form->getValues(); //filtered valid array of values
$username = $form->getValue('username');
}
}
$this->view->form = $form;
I think it's because of wrong implementation of validators.
Could you try to implement InputProviderInterface on your form? Basic example is given in the docs. There it is set on an Element, but you can do this on your form too. This interface define getInputSpecification where you have to return an array with filter and validator specification.
Related
I used zf2 authentication for authenticate user in my project.I saved Harib in my user table as user name but if i use my user name Harib then its accept or if i use harib then its not accept,i want to remove case sensitivity of user name so both Harib or harib access how i fix this?
Here is my code:
public function loginAction()
{
$this->layout('layout/login-layout.phtml');
$login_error = false;
$loginForm = new LoginForm();
$form_elements = json_encode($loginForm->form_elements);
if ($this->request->isPost()) {
$post = $this->request->getPost();
$loginForm->setData($post);
if ($loginForm->isValid()) {
$hashed_string = '';
if(
array_key_exists('hashed_input' , $post) &&
$post['hashed_input'] != '' &&
strpos(urldecode($this->params('redirect')) , 'programdetailrequest') !== false
) {
$hashed_string = $post['hashed_input'];
}
$data = $loginForm->getData();
$authService = $this->getServiceLocator()->get('doctrine.authenticationservice.odm_default');
$adapter = $authService->getAdapter();
$adapter->setIdentityValue($data['username']);
$adapter->setCredentialValue(md5($data['password']));
$authResult = $authService->authenticate();
if($authResult->isValid()){
$identity = $authResult->getIdentity();
if( is_object($identity) && method_exists($identity, 'getData') ){
$user_data = $identity->getData();
$authService->getStorage()->write($identity);
// for remeber checkbox
if ($post['rememberme']) {
$token = new UserToken();
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//if same user already running from other browser then remove previous token.
$check_token = $dm->getRepository('Admin\Document\UserToken')->findOneBy(array( "user_id.id" => $user_data['id'] ));
if (is_object($check_token) && !is_null($check_token)) {
$remove_token = $dm->createQueryBuilder('Admin\Document\UserToken')
->remove()
->field('id')->equals($check_token->id)
->getQuery()->execute();
}
//create token
$user = $dm->getRepository('Admin\Document\User')->findOneBy(array( "id" => $user_data['id'] ));
$token->setProperty('user_id', $user);
$token->setProperty('dataentered', new \MongoDate());
$dm->persist($token);
$dm->flush($token);
//create cookie
if(is_object($token) && property_exists($token, 'id')){
$time = time() + (60 * 60 * 24 * 30); // 1 month
setcookie('token', $token->getProperty('id'), $time, '/');
}
}
if ($user_data['user_type'] == 'onlinemarketer') {
$this->redirect()->toRoute('admin_program_meta');
} elseif ($user_data['user_type'] == 'bucharestofficemanager') {
$this->redirect()->toRoute('admin_program_detail_request');
} else {
if ($this->params('redirect') && urldecode($this->params('redirect')) !== '/logout/') {
$server_url = $this->getRequest()->getUri()->getScheme() . '://' . $this->getRequest()->getUri()->getHost().urldecode($this->params('redirect') . $hashed_string);
return $this->redirect()->toUrl($server_url);
}
return $this->redirect()->toRoute('admin_index');
}
}
} else {
$identity = false;
$login_error = true;
}
}
}
return new ViewModel(array(
'loginForm' => $loginForm,
'form_elements' =>$form_elements,
'login_error' => $login_error,
));
}
and here is my login form code:
<?php
namespace Admin\Form;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
class LoginForm extends Form implements InputFilterAwareInterface
{
protected $inputFilter;
public $form_elements = array(
array(
'name' => 'username',
'attributes' => array(
'id' => 'username',
'type' => 'text',
'error_msg' => 'Enter Valid Username',
'data-parsley-required' => 'true',
'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{1,50}$',
'data-parsley-trigger' => 'change'
),
'options' => array(
'label' => 'User Name'
),
'validation' => array(
'required'=>true,
'filters'=> array(
array('name'=>'StripTags'),
array('name'=>'StringTrim')
),
'validators'=>array(
array('name'=>'Regex',
'options'=> array(
'pattern' => '/^[a-z0-9_.-]{1,50}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
)
)
)
)
),
array(
'name' => 'password',
'attributes' => array(
'id' => 'password',
'type' => 'password',
'error_msg' => 'Enter Valid Password',
'data-parsley-required' => 'true',
'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{6,25}$',
'data-parsley-trigger' => 'change'
),
'options' => array(
'label' => 'Password'
),
'validation' => array(
'required' => true,
'filters'=> array(
array('name'=>'StripTags'),
array('name'=>'StringTrim')
),
'validators'=>array(
array('name'=>'Regex',
'options'=> array(
'pattern' => '/^[a-z0-9_.-]{6,25}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
)
)
)
)
),
array(
'name' => 'hashed_input',
'attributes' => array(
'type' => 'hidden',
'id' => 'hashed_input',
'value' => ''
)
),
array(
'name' => 'rememberme',
'attributes' => array(
'value' => 1,
'id' => 'rememberme',
'type' => 'Checkbox'
),
'options' => array(
'label' => 'Remember Me',
'use_hidden_element' => false,
)
),
array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Log in',
'id' => 'submitbutton'
)
)
);
public function __construct()
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->setAttribute('data-parsley-validate', '');
$this->setAttribute('data-elements', json_encode($this->form_elements));
$this->setAttribute('autocomplete', 'off');
for($i=0;$i<count($this->form_elements);$i++){
$elements=$this->form_elements[$i];
$this->add($elements);
}
}
public function getInputFilter($action=false)
{
if(!$this->inputFilter){
$inputFilter = new InputFilter();
$factory = new InputFactory();
for($i=0;$i<count($this->form_elements);$i++){
if(array_key_exists('validation',$this->form_elements[$i])){
$this->form_elements[$i]['validation']['name']=$this->form_elements[$i]['name'];
$inputFilter->add($factory->createInput( $this->form_elements[$i]['validation'] ));
}
}
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
how we remove case sensitivity of user name so both Harib or harib accepted?
Add a filter StringToLower in your loginform on the element user_id.
For this, the class that defines your loginform must implement InputFilterProviderInterface and you must add in the getInputFilterSpecification method as follows :
public function getInputFilterSpecification()
{
return [
'username' => [
'name' => 'username',
'required' => true,
'filters' => [
'name' => 'StringToLower',
'name'=>'StripTags',
'name'=>'StringTrim'
],
validators => [
[
'name'=>'Regex',
'options'=> [
'pattern' => '/^[a-z0-9_.-]{1,50}+$/',
'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
]
]
]
],
'password' => [
'name' => 'password',
'required' => true,
'filters' => [
array('name'=>'StripTags'),
array('name'=>'StringTrim')
],
'validators' => [
[
'name'=>'Regex',
'options'=> [
'pattern' => '/^[a-z0-9_.-]{6,25}+$/',
'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
]
]
]
]
];
}
So you are assured that the value returned in the post is in lowercase.
Since you're using MongoDB, you could use a regex to get the user name from the database.
Suggestion 1:
In your example that would be:
db.stuff.find( { foo: /^bar$/i } );
Suggestion 2:
You can Use $options => i for case insensitive search. Giving some possible examples required for string match.
Exact case insensitive string
db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
Contains string
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
Start with string
db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
End with string
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
Doesn't Contains string
db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
More about regex in MongoDb here: https://docs.mongodb.com/manual/reference/operator/query/regex/index.html
You may do this in two ways. Either you may create a custom authentication adapter or override a method of the default authentication adapter. I recommend that override that method which is easier than creating custom adapter.
So here is the method CredentialTreatmentAdapter::authenticateCreateSelect(). If you look up around 94 line (of zf 2.5) of that method from zend-authentication component then you would find the following line.
$dbSelect->from($this->tableName)
->columns(['*', $credentialExpression])
// See the making of where clause
->where(new SqlOp($this->identityColumn, '=', $this->identity));
Here we are going to make our changes. Now lets override that method by extending Zend\Authentication\Adapter\DbTable. We would make a where clause which would search for both Harib or harib therefore. See the following extended CustomDbTable::class.
<?php
namespace Define\Your\Own\Namespace;
use Zend\Authentication\Adapter\DbTable;
class CustomDbTable extends DbTable
{
protected function authenticateCreateSelect()
{
// build credential expression
if (empty($this->credentialTreatment) || (strpos($this->credentialTreatment, '?') === false)) {
$this->credentialTreatment = '?';
}
$credentialExpression = new SqlExpr(
'(CASE WHEN ?' . ' = ' . $this->credentialTreatment . ' THEN 1 ELSE 0 END) AS ?',
array($this->credentialColumn, $this->credential, 'zend_auth_credential_match'),
array(SqlExpr::TYPE_IDENTIFIER, SqlExpr::TYPE_VALUE, SqlExpr::TYPE_IDENTIFIER)
);
// Here is the catch
$where = new \Zend\Db\Sql\Where();
$where->nest()
->equalTo($this->identityColumn, $this->identity)
->or
->equalTo($this->identityColumn, strtolower($this->identity))
->unnest();
// get select
$dbSelect = clone $this->getDbSelect();
$dbSelect->from($this->tableName)
->columns(array('*', $credentialExpression))
->where($where); // Here we are making our own where clause
return $dbSelect;
}
}
Now custom authentication adapter is ready. You need to use this one inside the factory for authentication service instead of Zend\Authentication\Adapter\DbTable as follows
'factories' => array(
// Auth service
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
// Use CustomDbTable instead of DbTable here
$customDbTable = new CustomDbTable($dbAdapter, 'tableName', 'usernameColumn', 'passwordColumn', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($customDbTable);
return $authService;
},
),
All are now set. That overridden method should be called whenever you call this one in your controller method:
$authResult = $authService->authenticate();
This is not tested. So you may need to change things where you need. Please fix those if needed.
Hope this would help you!
Basically I'm trying to create a login, the email validation doesn't seem to pass. I've been looking around for an example but I'm genuinely not sure, doing it statically seems easy enough, however I vaguely suspect using static method would be incorrect to use as a login method(perhaps I'm over thinking it)
<?php
require ("Database.class.php");
class Login
{
private
$email,
$password,
$database,
$db = null;
public function __construct()
{
$this->db = new Database;
}
public function validEmail($email)
{
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
}
public function emptyPassword($password)
{
return(empty($password) !== TRUE);
}
public function validPassword($password)
{
$query = $this->db->prepare("select * from username");
return $query->fetch(PDO::FETCH_ASSOC);
}
}
<?php
require "classes/Login.class.php";
require "loadclasses.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $pass = "";
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$email = $post['email-login'];
$pass = $post['password-login'];
$errors = array();
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address'
),
'password-login' => array(
'validate' => 'emptyPassword',
'message' => 'Password required'
)
);
$login = new Login();
foreach($fields as $key => $value)
{
$validation_result = $login->$value['validate']($value);
if(!$validation_result)
{
$errors[] = ['name' => $key, 'error' => $value['message']];
}
}
if(empty($errors))
{
$success = ['response' => 'true'];
session_start();
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
As mentioned I'm aware I could do something similar to this:
$errors = array();
$fields = array(
'username' => array(
'validator' => 'validateUsername',
'message' => 'Username must be between three and fourteen alphanumeric characters'
),
'email' => array(
'validator' => 'validateEmail',
'message' => 'Please enter a valid email',
),
'password' => array(
'validator' => 'validatePassword',
'message' => 'Password must be a minimum of seven characters'
)
);
if(!Validation::validateRepeatPassword($password, $repeatPassword))
{
$errors[] = ["name" => "repeatPassword", "error" => "Passwords must match"];
}
foreach($post as $key => $value)
{
if(isset($fields[$key]))
{
if(!Validation::{$fields[$key]['validator']}($value))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
}
The main problem as I mentioned is I'm fairly sure that would be the wrong way to approach this problem
The problem seems to be here:
$validation_result = $login->$value['validate']($value);
When you do that, you're actually passing $value which is an array (according to the foreach). You're not actually passing the email
So, according to your code, you should change your validation array to something like:
$fields = array(
'email-login' => array(
'validate' => 'validEmail',
'message' => 'Enter a valid email address',
'value' => $email,
),
'password-login' => array(
'validate' => 'emptyPassword',
'message' => 'Password required',
'value' => $pass,
)
);
And then, change your validation line to:
$validation_result = $login->$value['validate']($value['value']);
I have a form that was working until I added two dropdown menus. Since then, upon the submission of the form I get the error:
haystack option is mandatory
This is my ProjectForm.php
<?php
namespace Project\Form;
use Zend\Form\Form;
use Zend\Form\Element\Text;
use Zend\Form\Fieldset;
use Zend\Form\Element\Select;
use Zend\Form\Element\Checkbox;
use Zend\Form\Element\Date;
use Zend\Config\Factory;
use Zend\Form\Element\Button;
use Zend\Form\Element\Textarea;
use Zend\Validator\Callback;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Form\Element\File;
class ProjectForm extends Form implements InputFilterProviderInterface {
const KEY_PROJECT_NAME = "project_name";
const KEY_PROJECT_DUE_DTTM = "project_due_dttm";
const KEY_PROJECT_DESCRIPTION = "project_description";
const KEY_PROJECT_CONFIG = "project_config";
const KEY_PROJECT_TYPES = "project_types";
const KEY_PROJECT_WORKFLOW_CONFIG = "project_workflow_config";
const KEY_PROJECT_WORKFLOW_TYPES = "project_workflow_types";
const KEY_PROJECT_FILE = "project_file";
const KEY_SAVE_BTN = "project_save_btn";
const KEY_CANCEL_BTN = "project_cancel_btn";
public function __construct($name = null, $options = array()) {
parent::__construct($name);
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'form-horizontal');
$name = new Text(self::KEY_PROJECT_NAME);
$name->setAttribute("id", self::KEY_PROJECT_NAME);
$name->setLabel("Name");
$duedttm = new Text(self::KEY_PROJECT_DUE_DTTM);
$duedttm->setAttribute("id", self::KEY_PROJECT_DUE_DTTM);
$duedttm->setLabel("Due Date");
$description = new Textarea(self::KEY_PROJECT_DESCRIPTION);
$description->setAttribute("id", self::KEY_PROJECT_DESCRIPTION);
$description->setLabel("Description");
$config = new Textarea(self::KEY_PROJECT_CONFIG);
$config->setAttribute("id", self::KEY_PROJECT_CONFIG);
$config->setLabel("Configuration");
$projectTypeDropDown = new Select(self::KEY_PROJECT_TYPES);
$projectTypeDropDown->setLabel('Project Type:');
$projectTypeDropDown->setValueOptions($options["project"]);
$wfConfig = new Textarea(self::KEY_PROJECT_WORKFLOW_CONFIG);
$wfConfig->setAttribute("id", self::KEY_PROJECT_WORKFLOW_CONFIG);
$wfConfig->setLabel("Workflow Configuration");
$projectWorkflowDropDown = new Select(self::KEY_PROJECT_WORKFLOW_TYPES);
$projectWorkflowDropDown->setLabel('Workflow Type:');
$projectWorkflowDropDown->setValueOptions(array());
$file = new File(self::KEY_PROJECT_FILE);
$file->setAttribute("id", self::KEY_PROJECT_FILE);
$file->setAttribute("multiple", true);
$file->setLabel("File");
$save = new Button(self::KEY_SAVE_BTN);
$save->setAttributes(array("id", self::KEY_SAVE_BTN));
$save->setLabel("Save");
$save->setValue("Save");
$cancel = new Button(self::KEY_CANCEL_BTN);
$cancel->setAttributes(array("id", self::KEY_CANCEL_BTN));
$cancel->setLabel("Cancel");
$this->add($name);
$this->add($duedttm);
$this->add($description);
$this->add($config);
$this->add($projectTypeDropDown);
$this->add($wfConfig);
$this->add($projectWorkflowDropDown);
$this->add($file);
$this->add($save);
$this->add($cancel);
}
public function isValidJSON($value, $options) {
try {
JSON::decode($value);
return true;
} catch (JSONException $e) {
return false;
}
}
public function isValidDateTime($value, $options) {
if (false === date_create($value)) {
return false;
}
return true;
}
/**
* (non-PHPdoc)
* #see \Zend\InputFilter\InputFilterProviderInterface::getInputFilterSpecification()
*/
public function getInputFilterSpecification() {
return array(
ProjectForm::KEY_PROJECT_CONFIG => array(
'required' => true,
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'validators' => array(
new Callback(
array(
$this,
'isValidJSON'
)),
),
),
ProjectForm::KEY_PROJECT_WORKFLOW_CONFIG => array(
'required' => false,
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'validators' => array(
new Callback(
array(
$this,
'isValidJSON'
)),
),
),
ProjectForm::KEY_PROJECT_DUE_DTTM => array(
'required' => false,
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'validators' => array(
new Callback(
array(
$this,
'isValidDateTime'
)),
),
),
);
}
}
I think I need to disable the inarray_validator by adding disable_inarray_validator' => true but I'm not sure where to add this.
Because of the version of Zend that I am using, I had to add this to the controller before validating the form:
// Make certain to merge the files info!
$post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//Deals with validation of dynamic form
$projectType = $projectTypes[$post["project_types"]];
$form->get('project_workflow_types')->setValueOptions($workflowTypes[$projectType]);
// set the form instance's data
$form->setData($post);
I suggest you pass an empty string as a unique valueOption. In your javascript you flush the <option> tags of the select to get rid of this empty option.
Also you will have to disable the default validator of the Select element by adding :
$projectWorkflowDropDown->setOptions(array('disable_inarray_validator' => true));
Or
$projectWorkflowDropDown->setDisableInArrayValidator(true);
If you don't add this option, when the form will be submitted, Zend Form will tell you the value send is not in the haystack provided when the form was built. This is a safety process which is very helpful in many cases, just not in your.
Actually I'm developing a simple file uploader.
In the ImageUploader.php file I define the getInputFilter function, all works unless I try to add a File\MimeType validator:
<?php
namespace Admin\Model;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\File\MimeType; //tried also with use Zend\Validator\File;
[...]
public function getInputFilter()
{
[...]
$inputFilter->add($factory->createInput(array(
'name' => 'image',
'required' => true,
'validators' => array(
array(
'name' => 'MimeType', //tried also with File\MimeType
'options' => array(
'mimeType' => array('image/jpeg'),
),
),
),
)));
[...]
}
What's the correct way to define a File\Validator\MimeType?
Thank you in advance.
Here is a sample from my project with a couple of other useful features (renaming for example):
use Zend\File\Transfer\Adapter\Http,
Zend\Validator\File\Size,
Zend\Validator\File\IsImage;
[...]
public function editAction() {
[...]
if ($request->isPost()) {
$params = $this->params()->fromPost();
$files = $this->params()->fromFiles();
$images = array();
if(!empty($files['main_image']['name'])) $images['main_image'] = $files['main_image']['name'];
if(!empty($files['detailed_image']['name'])) $images['detailed_image'] = $files['detailed_image']['name'];
if(!empty($images)) {
$adapter = new Http();
$size = new Size(array('max'=>1000000));
$is_image = new IsImage();
$image_errors = array();
foreach ($images as $field => $filename) {
$adapter->setValidators(array($size,$is_image), $filename);
if (!$adapter->isValid($filename)) {
$adapter_errors = $adapter->getMessages();
$errors = array();
foreach($adapter_errors as $key=>$row) {
$errors[] = $row;
}
if(!empty($errors)) {
array_push($image_errors, $errors);
$form->setMessages(array($field => $errors));
}
} else {
$adapter->setDestination(IMAGES_PATH);
$fileinfo = $adapter->getFileInfo();
preg_match('/.+\/(.+)/', $fileinfo[$field]['type'], $matches);
$extension = $matches[1];
$old_filename = $item->__get($field);
$new_filename = $item->id.'_'.$field.'.'.$extension;
$adapter->addFilter('File\Rename',
array(
'target' => IMAGES_PATH.$new_filename,
'overwrite' => true,
)
);
if($adapter->receive($fileinfo[$field]['name'])) {
if(!empty($old_filename) && $old_filename != $new_filename &&
file_exists(IMAGES_PATH.$old_filename)) {
unlink(IMAGES_PATH.$old_filename);
}
$params[$field] = $new_filename;
}
}
}
}
}
[...]
}
[...]
The code however could be refactored to move the logic to some lib or model.
Not sure which version you are using now but with Zendframework 2.4 you can now do this. Hope this helps.
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'fileupload',
'required' => true,
'allow_empty' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Zend\Validator\File\UploadFile',
'name' => 'Zend\Validator\File\MimeType',
'options' => array(
'mimeType' => 'audio, video, image',
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
How can i validate something i did not get from a form. I want to validate my variable and i want this rule to be is_uniqe() to check for duplicates.
I have tried setting a rule in the $rules array as array( 'field' => $this->characterNAME, 'rules' => 'is_unique[members.char_name]) yet no effect i tried calling the is_unique() on its own yet no effect and i tried to asign the variable to $_POST['charNAME'] = $this->characterNAME; and then pass that to set_rules() yet no effect.
How can i validate my variable ?
My code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Registration extends CI_Controller {
var $characterNAME = "";
var $characterCORP = "";
var $characterALLY = "";
var $characterJDAT = "";
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Registration_model', 'reg');
}
public function index()
{
$this->load->view('registration_view');
}
function insert()
{
$rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|min_length[6]|max_length[250]|is_unique[members.username]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|min_length[6]|max_length[250]|md5'
),
array(
'field' => 'apiid',
'label' => 'apiid',
'rules' => 'required|integer|min_length[6]|max_length[250]|callback_api_check[' . $this->input->post('apikey') . ']'
),
array(
'field' => 'apikey',
'label' => 'apikey',
'rules' => 'required|min_length[6]|max_length[255]'
),
);
$_POST['charNAME'] = $this->characterNAME;
$this->form_validation->set_rules('charNAME', 'CharacterName', 'is_unique[members.char_name]');
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE)
{
$this->load->view('registration_view');
} else {
// PROCESS REGISTRATION
$this->reg->add_user($_POST['username'], $_POST['password'], $_POST['apiid'], $_POST['apikey'], $this->characterNAME, $this->characterCORP, $this->characterALLY, $this->characterJDAT);
// REDIRECT
$this->load->view('registration_done');
}
}
function api_check($apiid, $apikey)
{
$url = 'http://api.eveonline.com/account/Characters.xml.aspx?keyID='.$apiid.'&vCode='.$apikey;
$xml = new DOMDocument();
$xml->load($url);
$chars = $xml->getElementsByTagName('row');
foreach ($chars as $character)
{
$charid = $character->attributes;
$curl = 'http://api.eveonline.com/eve/CharacterInfo.xml.aspx?keyID='. $apiid . '&vCode='.$apikey . '&characterID=' . $charid->item(1)->nodeValue;
$cxml = new DOMDocument();
$cxml->load($curl);
$corp = $cxml->getElementsByTagName("corporation");
$ally = $cxml->getElementsByTagName("alliance");
$char = $cxml->getElementsByTagName("characterName");
$jdat = $cxml->getElementsByTagName("corporationDate");
// Check database instead
if($this->reg->validate_entity($corp->item(0)->nodeValue) || $this->reg->validate_entity($ally->item(0)->nodeValue))
{
$this->characterNAME = $char->item(0)->nodeValue;
$this->characterCORP = $corp->item(0)->nodeValue;
$this->characterALLY = $ally->item(0)->nodeValue;
$this->characterJDAT = $jdat->item(0)->nodeValue;
return true;
}
}
$this->form_validation->set_message('api_check','None of the characters on this account are allowed to join.');
return false;
}
}
You can validate that your form input isn't a duplicate by calling the is_unique function directly, via (example):
$this->form_validation->is_unique($email, 'users.email');
This will return a boolean true/false. True = Is Unique -- in this case
Therefore, you can put that in an if() and check it that way...
Hope this helps