/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $flag = true; $value = $validator->getValue($attribute); $errorCode = $this->getOption('code'); if (!is_array($value)) { $message = '参数必须是数组'; $validator->appendMessage(new Message($message, $attribute, 'Nums')); return false; } $countVal = count($value); $ruleMin = $this->getOption('min'); $ruleMax = $this->getOption('max'); if ($ruleMin == $ruleMax) { if ($countVal < $ruleMin) { $flag = false; } } else { if ($countVal < $ruleMin || $countVal > $ruleMax) { $flag = false; } } if (!$flag) { $message = $this->getOption('message'); if (!$message) { $message = 'The num is not valid'; } $validator->appendMessage(new Message($message, $attribute, 'Nums')); return false; } return true; }
/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $flag = true; $reqType = $validator->getValue($attribute); // 待校验的文件集合 $fileType = $this->getOption('filetype'); // 合法的文件类型集合 $errorCode = $this->getOption('code'); foreach ($reqType as $file) { $extArr = explode('.', $file); $ext = array_pop($extArr); if (!in_array($ext, $fileType)) { $flag = false; break; } } if (!$flag) { $message = $this->getOption('message'); if (!$message) { $message = 'The filetype is not valid'; } $validator->appendMessage(new Message($message, $attribute, 'filetype')); return false; } return true; }
public function validation() { $validator = new Phalcon\Validation(); $validator->add('title', new StringLength(['max' => 200, 'message' => '标题的长度不能超过200字'])); $validator->add('abstract', new StringLength(['max' => 400, 'message' => '摘要的长度不能超过400字'])); return $this->validate($validator); }
/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * * @return boolean */ public function validate($validator, $attribute) { // If the attribute is name we must stop the chain if ($attribute == 'name') { $validator->setOption('cancelOnFail', true); } //... }
public function testAlreadyTakenUniquenessWithCustomMessage() { $validation = new \Phalcon\Validation(); $uniquenessOptions = array('table' => 'users', 'column' => 'login', 'message' => 'Login already taken.'); $uniqueness = new Uniqueness($uniquenessOptions, $this->getDbStub()); $validation->add('login', $uniqueness); $messages = $validation->validate(array('login' => 'login_taken')); $this->assertCount(1, $messages); $this->assertEquals('Login already taken.', $messages[0]); }
public function testException() { $validation = new \Phalcon\Validation(); $validation->add('unique', new Unique()); $values = array('unique' => 'foo'); try { $validation->validate($values); throw new \Exception('Not this exception.'); } catch (\Exception $ex) { $this->assertInstanceOf('Vegas\\Validation\\Validator\\Unique\\Exception\\ModelNameNotSetException', $ex); } }
public function testException() { $validation = new \Phalcon\Validation(); $validation->add('field1', new SameAs()); $values = array('field1' => 'foo', 'field2' => 'foo'); try { $validation->validate($values); throw new \Exception('Not this exception.'); } catch (\Exception $ex) { $this->assertInstanceOf('Vegas\\Validation\\Validator\\SameAs\\Exception\\MatchNotSetException', $ex); } }
/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $value = $validator->getValue($attribute); if (!filter_var($value, FILTER_VALIDATE_URL)) { $message = $this->getOption('message'); if (!$message) { $message = self::INVALID_URL; } $validator->appendMessage(new Message($message, $attribute, 'Url')); return false; } return true; }
/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $value = $validator->getValue($attribute); if (filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) { $message = $this->getOption('message'); if (!$message) { $message = 'The IP is not valid'; } $validator->appendMessage(new Message($message, $attribute, 'Ip')); return false; } return true; }
public function formValidate() { $validation = new Phalcon\Validation(); $validation->add('name', new PresenceOf(array('message' => 'name field is required'))); $validation->add('website', new PresenceOf(array('message' => 'website field is required'))); $validation->add('telephone', new PresenceOf(array('message' => 'telephone field is required'))); $validation->add('event_info', new PresenceOf(array('message' => 'event information field is required'))); $validation->add('street', new PresenceOf(array('message' => 'street field is required'))); $validation->add('city', new PresenceOf(array('message' => 'city field is required'))); $validation->add('country', new PresenceOf(array('message' => 'city field is required'))); $validation->add('category', new PresenceOf(array('message' => 'category field is required'))); return $validation->validate($_POST); }
/** * Executes the uniqueness validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $table = $this->getOption('table'); $column = $this->getOption('column'); $result = $this->db->fetchOne(sprintf('SELECT COUNT(*) as count FROM %s WHERE %s = ?', $table, $column), \Phalcon\Db::FETCH_ASSOC, array($validator->getValue($attribute))); if ($result['count']) { $message = $this->getOption('message'); if (null === $message) { $message = 'Already taken. Choose another!'; } $validator->appendMessage(new Message($message, $attribute, 'Uniqueness')); return false; } return true; }
/** * Executes the validation * * @param Phalcon\Validation $validator * @param string $attribute * @return boolean */ public function validate($validator, $attribute) { $value = $validator->getValue($attribute); if ($value !== null && $value !== '') { if (!is_numeric($value) || !preg_match('/^[0-9\\.]+$/', $value)) { $message = $this->getOption('message'); if ($message) { $validator->appendMessage(new Message($message, $attribute, 'Numericality')); } else { $validator->appendMessage(new Message('This field must be a number', $attribute, 'Numericality')); } return false; } } return true; }
/** * @param \Vegas\Forms\Element\Cloneable\Row $row * @param array $values * @return \Phalcon\Validation\Message\Group */ protected function validateRowElements(\Vegas\Forms\Element\Cloneable\Row $row, $values) { $messagesGroup = new \Phalcon\Validation\Message\Group(); $validation = new \Phalcon\Validation(); foreach ($row->getElements() as $key => $element) { if (!$element->getValidators()) { break; } foreach ($element->getValidators() as $validator) { $validation->add($key, $validator); } } if (count($validation->getValidators())) { $messagesGroup = $validation->validate($values); } return $messagesGroup; }
public function getMessages() { $messages = array(); foreach (parent::getMessages() as $message) { switch ($message->getType()) { case 'PresenceOf': $messages[] = 'The field ' . $message->getField() . ' is mandatory'; break; } } return $messages; }
public function formValidate() { $validation = new Phalcon\Validation(); $validation->add('name', new PresenceOf(array('message' => 'name field is required'))); $validation->add('details', new PresenceOf(array('message' => 'details field is required'))); $validation->add('price', new PresenceOf(array('message' => 'price field is required'))); $validation->add('thing_condition_id', new PresenceOf(array('message' => 'condition field is required'))); $validation->add('thing_category_id', new PresenceOf(array('message' => 'category field is required'))); return $validation->validate($_POST); }
/** * @Get('/Simple/{id:[0-9]+}') */ public function simple_get_gAction($id) { $ans = []; try { $validation = new Phalcon\Validation(); $validation->add('item_id', new PresenceOf(['message' => 'item_id is needed'])); $validation->add('item_id', new Regex(['pattern' => '/[0-9]{0,10}/u', 'message' => "item_id need a number"])); $messages = $validation->validate($_GET); if (count($messages)) { foreach ($messages as $message) { throw new Exception($message, 102); } } $item_id = $this->request->getQuery('item_id'); $simple = SurveySimple::findFirst(['item=?0 AND user_id=?1', 'bind' => [$item_id, $id]]); if ($simple == null) { throw new Exception('item can not find', 1002); } $ans['value'] = $simple->value; } catch (Exception $e) { $ans['value'] = -1; Utils::makeError($e, $ans); } finally { echo json_encode($ans); } }
/** * Register a new user using given values * * @param array Values * * @return Array of error messages */ public function registerUser(array $values) { $validation = new \Phalcon\Validation(); $validation->add('username', new PresenceOf()); $validation->add('email', new PresenceOf()); $validation->add('email', new Email()); $validation->add('password', new StringLength(array('min' => 8))); $validation->add('password', new PresenceOf()); $validation->add('password_confirm', new PresenceOf()); $validation->add('password_confirm', new Confirmation(array('message' => 'The passwords are not the same', 'with' => 'password'))); $messages = $validation->validate($values); if (count($messages) !== 0) { return $messages; } $user = new $this->_className(); $user->username = $values['username']; $user->password = $this->hash($values['password']); $user->email = $values['email']; $user->password_version = self::$_latest_password_version; $user->save(); return $user->getMessages(); }
public function testOptionAllowEmpty() { $expectedMessages = Phalcon\Validation\Message\Group::__set_state(array('_messages' => array(0 => Phalcon\Validation\Message::__set_state(array('_type' => 'Confirmation', '_message' => 'Field password must be the same as password2', '_field' => 'password', '_code' => '0'))))); // allowEmpty: true $validation = new Phalcon\Validation(); $validation->add('password', new Confirmation(array('allowEmpty' => true, 'with' => 'password2'))); $this->assertEquals(count($validation->validate(array('password' => 'test123', 'password2' => 'test123'))), 0); $this->assertEquals(count($validation->validate(array('password' => null, 'password2' => 'test123'))), 0); // END // allowEmpty: false $validation = new Phalcon\Validation(); $validation->add('password', new Confirmation(array('allowEmpty' => false, 'with' => 'password2'))); $this->assertEquals(count($validation->validate(array('password' => 'test123', 'password2' => 'test123'))), 0); $messages = $validation->validate(array('password' => null, 'password2' => 'test123')); $this->assertEquals(count($messages), 1); $this->assertEquals($messages, $expectedMessages); // END // allowEmpty: DEFAULT $validation = new Phalcon\Validation(); $validation->add('password', new Confirmation(array('with' => 'password2'))); $this->assertEquals(count($validation->validate(array('password' => 'test123', 'password2' => 'test123'))), 0); $messages = $validation->validate(array('password' => null, 'password2' => 'test123')); $this->assertEquals(count($messages), 1); $this->assertEquals($messages, $expectedMessages); // END }
<?php use Phalcon\Validation\Validator\PresenceOf, Phalcon\Validation\Validator\Regex; $validation = new Phalcon\Validation(); $validation->add('telephone', new PresenceOf(array('message' => 'The telephone is required', 'cancelOnFail' => true)))->add('telephone', new Regex(array('message' => 'The telephone is required', 'pattern' => '/\\+44 [0-9]+/')))->add('telephone', new StringLength(array('minimumMessage' => 'The telephone is required', 'pattern' => '/\\+44 [0-9]+/')));
public function testValidationSetLabels() { $_POST = array('email' => '', 'firstname' => ''); $validation = new Phalcon\Validation(); $validation->add('email', new PresenceOf(array('message' => 'The :field is required'))); $validation->add('email', new Email(array('message' => 'The :field must be email', 'label' => 'E-mail'))); $validation->add('firstname', new PresenceOf(array('message' => 'The :field is required'))); $validation->add('firstname', new StringLength(array('min' => 4, 'messageMinimum' => 'The :field is too short'))); $validation->setLabels(array('firstname' => 'First name')); $messages = $validation->validate($_POST); $expectedMessages = Phalcon\Validation\Message\Group::__set_state(array('_messages' => array(0 => Phalcon\Validation\Message::__set_state(array('_type' => 'PresenceOf', '_message' => 'The email is required', '_field' => 'email', '_code' => '0')), 1 => Phalcon\Validation\Message::__set_state(array('_type' => 'Email', '_message' => 'The E-mail must be email', '_field' => 'email', '_code' => '0')), 2 => Phalcon\Validation\Message::__set_state(array('_type' => 'PresenceOf', '_message' => 'The First name is required', '_field' => 'firstname', '_code' => '0')), 3 => Phalcon\Validation\Message::__set_state(array('_type' => 'TooShort', '_message' => 'The First name is too short', '_field' => 'firstname', '_code' => '0'))))); $this->assertEquals($expectedMessages, $messages); }
/** * validate full model using all fields and data in a single (1 deep) array * @param bool $validateFullModel validate full model or only changed fields * @return \Phalcon\Validation\Message\Group */ public function performValidation($validateFullModel = false) { // create a Phalcon validator and collect all model validations $validation = new \Phalcon\Validation(); $validation_data = array(); $all_nodes = $this->internalData->getFlatNodes(); foreach ($all_nodes as $key => $node) { if ($validateFullModel || $node->isFieldChanged()) { $node_validators = $node->getValidators(); foreach ($node_validators as $item_validator) { $validation->add($key, $item_validator); } if (count($node_validators) > 0) { $validation_data[$key] = $node->__toString(); } } } if (count($validation_data) > 0) { $messages = $validation->validate($validation_data); } else { $messages = new \Phalcon\Validation\Message\Group(); } return $messages; }
/** * Validate One Element * * @param $oElement \Phalcon\Forms\ElementInterface || \BP\Phalcon\Forms\Form * @param $mData * * @return \Phalcon\Validation\Message\Group */ protected function validateElement($oElement, $mData) { if ($oElement instanceof \BP\Phalcon\Forms\Form) { return $oElement->isValid($mData, true); } else { $aValidators = $oElement->getValidators(); for ($i = 0, $c = count($aValidators), $aPreparedValidators = []; $i < $c; $i++) { $aPreparedValidators[] = [$oElement->getName(), $aValidators[$i]]; } if (count($aPreparedValidators) != 0) { $oValidation = new \Phalcon\Validation($aPreparedValidators); } $aFilters = $oElement->getFilters(); if (count($aFilters) != 0) { $oValidation->setFilters($oElement->getName(), $aFilters); } return $oValidation->validate($mData); } }
public function updateAction() { $ans = []; try { if (!$this->request->isPost()) { throw new Exception('请用正确的方式访问我们的API', 99); } $validation = new Phalcon\Validation(); $validation->add('id', new PresenceOf(['message' => 'id is needed.'])); $validation->add('id', new Regex(['pattern' => '/[0-9]{1,10}/u', 'message' => 'please give us a number.'])); $validation->add('name', new PresenceOf(['message' => 'name is needed'])); $validation->add('name', new StringLength(['max' => 30, 'messageMaximum' => 'The name is too long.'])); $messages = $validation->validate($_POST); foreach ($messages as $message) { throw new Exception($message, 102); } $id = $this->request->getPost('id'); $name = $this->request->getPost('name'); $userGroup = UserGroup::findFirst($id); if ($userGroup == null) { throw new Exception('id is not find', 1201); } $userGroup->id = $id; $userGroup->name = $name; $succeed = $userGroup->save(); if ($succeed) { $ans['ret'] = 0; } else { foreach ($userGroup->getMessages() as $message) { throw new Exception($message, 100); } } } catch (Exception $e) { $ans['ret'] = -1; Utils::makeError($e, $ans); } finally { echo json_encode($ans); } }
public function testValidationFiltering() { $validation = new Phalcon\Validation(); $validation->setDI(new Phalcon\DI\FactoryDefault()); $validation->add('name', new PresenceOf(array('message' => 'The name is required')))->add('email', new PresenceOf(array('message' => 'The email is required'))); $validation->setFilters('name', 'trim'); $validation->setFilters('email', 'trim'); $_POST = array('name' => ' ', 'email' => ' '); $messages = $validation->validate($_POST); $this->assertEquals(count($messages), 2); $filtered = $messages->filter('email'); $expectedMessages = array(0 => Phalcon\Validation\Message::__set_state(array('_type' => 'PresenceOf', '_message' => 'The email is required', '_field' => 'email'))); $this->assertEquals($filtered, $expectedMessages); $_POST = array(); }
public function newAction() { if ($this->request->isPost()) { // validation $validation = new Phalcon\Validation(); $validation->add('name', new PresenceOf(array('message' => 'name field is required'))); $validation->add('location', new PresenceOf(array('message' => 'location field is required'))); $validation->add('details', new PresenceOf(array('message' => 'details field is required'))); $validation->add('price', new PresenceOf(array('message' => 'price field is required'))); $validation->add('brand', new PresenceOf(array('message' => 'brand field is required'))); $validation->add('model', new PresenceOf(array('message' => 'model field is required'))); $validation->add('year_model', new PresenceOf(array('message' => 'year model field is required'))); $validation->add('condition', new PresenceOf(array('message' => 'condition field is required'))); $validation->add('body_type', new PresenceOf(array('message' => 'body type field is required'))); $validation->add('transmission', new PresenceOf(array('message' => 'transmission field is required'))); $validation->add('mileage', new PresenceOf(array('message' => 'mileage field is required'))); $validation->add('fuel_type', new PresenceOf(array('message' => 'fuel type field is required'))); $messages = $validation->validate($_POST); if (count($messages)) { $this->view->disable(); $errorMsg = ''; foreach ($messages as $msg) { $errorMsg .= $msg . "<br>"; } $this->flash->error('<button type="button" class="close" data-dismiss="alert">×</button>' . $errorMsg); return $this->response->redirect('car_and_truck/new/'); } else { $this->view->disable(); echo "validation is either failed or passed"; } $name = $this->request->getPost('name'); $location = $this->request->getPost("location"); $details = $this->request->getPost("details"); $price = $this->request->getPost("price"); $brand = $this->request->getPost("brand"); $model = $this->request->getPost("model"); $yearModel = $this->request->getPost("year_model"); $condition = $this->request->getPost("condition"); $bodyType = $this->request->getPost("body_type"); $transmission = $this->request->getPost("transmission"); $mileage = $this->request->getPost("mileage"); $fuelType = $this->request->getPost("fuel_type"); $image = $this->request->getPost('image'); $auto = new Automotives(); $auto->created = date('Y-m-d H:i:s'); $auto->modified = date('Y-m-d H:i:s'); $auto->member_id = 1; $auto->location = $location; $auto->name = $name; $auto->details = $details; $auto->price = $price; $auto->brand = $brand; $auto->model = $model; $auto->year_model = $yearModel; $auto->condition_id = $condition; $auto->body_type = $bodyType; $auto->transmission = $transmission; $auto->mileage = $mileage; $auto->fuel_type_id = $fuelType; $this->view->disable(); if ($auto->create()) { $id = $auto->id; if ($this->request->hasFiles() == true) { $uploads = $this->request->getUploadedFiles(); $isUploaded = false; $ctr = 1; foreach ($uploads as $upload) { # define a "unique" name and a path to where our file must go $fileName = $upload->getname(); $fileInfo = new SplFileInfo($fileName); $fileExt = $fileInfo->getExtension(); $fileExt = strtolower($fileExt); $newFileName = substr(md5(uniqid(rand(), true)), 0, 10) . date('ymdhis') . '.' . $fileExt; $fileImageExt = array('jpeg', 'jpg', 'png'); $fileType = ''; $filePath = ''; $path = ''; if (in_array($fileExt, $fileImageExt)) { $path = 'img/car/' . $newFileName; $filePath = 'img/car/'; //$fileType = 'Image'; } # move the file and simultaneously check if everything was ok $upload->moveTo($path) ? $isUploaded = true : ($isUploaded = false); if ($isUploaded) { $thingPhotos = new AutomotivePhotos(); $thingPhotos->created = date('Y-m-d H:i:s'); $thingPhotos->modified = date('Y-m-d H:i:s'); $thingPhotos->member_id = 1; $thingPhotos->automotive_id = $id; $thingPhotos->file_path = $filePath; $thingPhotos->filename = $newFileName; $thingPhotos->caption = $this->request->getPost('caption'); $ctr++; if ($thingPhotos->create()) { echo "success"; } else { print_r($thingPhotos->getMessages()); } } } } } else { print_r($auto->getMessages()); } } $this->view->setVars(['carConditions' => AutomotiveConditions::find(), 'carFuels' => AutomotiveFuels::find()]); }
public function formValidate() { $validation = new Phalcon\Validation(); $validation->add('position', new PresenceOf(array('message' => 'position field is required'))); $validation->add('job_category_id', new PresenceOf(array('message' => 'job category field is required'))); $validation->add('job_description', new PresenceOf(array('message' => 'job description field is required'))); $validation->add('requirements', new PresenceOf(array('message' => 'requirements field is required'))); $validation->add('benefits', new PresenceOf(array('message' => 'benefits field is required'))); $validation->add('how_to_apply', new PresenceOf(array('message' => 'how to apply field is required'))); $validation->add('logo', new PresenceOf(array('message' => 'logo/image is required'))); $validation->add('salary_from', new PresenceOf(array('message' => 'salary from field is required'))); $validation->add('salary_to', new PresenceOf(array('message' => 'salary to field is required'))); $validation->add('company', new PresenceOf(array('message' => 'company field is required'))); $validation->add('website', new PresenceOf(array('message' => 'website field is required'))); $validation->add('telephone', new PresenceOf(array('message' => 'telephone field is required'))); $validation->add('email', new PresenceOf(array('message' => 'email field is required'))); $validation->add('street', new PresenceOf(array('message' => 'street field is required'))); $validation->add('city', new PresenceOf(array('message' => 'position field is required'))); $validation->add('country_id', new PresenceOf(array('message' => 'position field is required'))); return $validation->validate($_POST); }
public function editAction() { $this->assets->collection('bottom-js')->addJs('js/moment/moment.min.js')->addJs('js/moment/ru.js')->addJs('js/datetimepicker/js/bootstrap-datetimepicker.js'); $this->assets->collection('css')->addCss('js/datetimepicker/css/bootstrap-datetimepicker.min.css'); $id = $this->dispatcher->getParam('id'); $banner = Banners::findFirst($id); if ($id && $banner) { if ($this->request->isPost()) { $old_banner_type = $banner->type; $old_banner_content = $banner->content; $data = $this->request->getPost(); $data['target_blank'] = (bool) $this->request->get('target_blank') ? '1' : '0'; if ($this->request->getPost('start_date')) { $start_date = date_parse_from_format('d.m.Y H:i', $data['start_date']); $data['start_date'] = mktime($start_date['hour'], $start_date['minute'], 0, $start_date['month'], $start_date['day'], $start_date['year']); } if ($this->request->getPost('end_date')) { $end_date = date_parse_from_format('d.m.Y H:i', $data['end_date']); $data['end_date'] = mktime($end_date['hour'], $end_date['minute'], 0, $end_date['month'], $end_date['day'], $end_date['year']); } if (($data['type'] == "image" || $data['type'] == "flash") && $data['source'] == "local") { $data['content'] = Banners::findFirst(array('id = :id:', 'bind' => array('id' => $data['content'])))->content; } $this->db->begin(); if ($banner->save($data, array('name', 'width', 'height', 'link', 'target_blank', 'priority', 'type', 'content', 'max_impressions', 'start_date', 'end_date', 'url_mask', 'advertiser_id')) == false) { $this->db->rollback(); foreach ($banner->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { if (($this->request->getPost('type') == "image" || $this->request->getPost('type') == "flash") && $this->request->getPost('source') == "file") { if ($this->request->hasFiles(true)) { $file = $this->request->getUploadedFiles()[0]; $validation = new \Phalcon\Validation(); $validation->add('file', new UploadValid()); if ($this->request->getPost('type') == "image") { $validation->add('file', new UploadType(array('allowed' => array('jpg', 'jpeg', 'png', 'gif')))); $validation->add('file', new UploadImage()); } elseif ($this->request->getPost('type') == "flash") { $validation->add('file', new UploadType(array('allowed' => array('swf')))); } $messages = $validation->validate($_FILES); if (count($messages)) { $this->db->rollback(); foreach ($validation->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { $extension = pathinfo($file->getName(), PATHINFO_EXTENSION); $name = $banner->id . '_' . time() . '.' . $extension; $file->moveTo(($this->request->getPost('type') == "image" ? $this->config->banners->imagePath : $this->config->banners->flashPath) . $name); if ($banner->save(array('content' => $name)) == false) { $this->db->rollback(); foreach ($banner->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { if (($old_banner_type == "image" || $old_banner_type == "flash") && !empty($old_banner_content)) { unlink(($old_banner_type == "image" ? $this->config->banners->imagePath : $this->config->banners->flashPath) . $old_banner_content); } $this->db->commit(); } } } else { $this->db->rollback(); $this->flashSession->error("Необходимо указать файл"); } } else { $this->db->commit(); } BannersZones::find(array("banner_id=:banner:", 'bind' => array('banner' => $banner->id)))->delete(); if ($this->request->getPost('zones')) { foreach ($this->request->getPost('zones') as $zone) { $zone = Zones::findFirst($zone); if ($zone) { $m = new BannersZones(); $m->banner_id = $banner->id; $m->zone_id = $zone->id; $m->create(); } } } return $this->response->redirect(array('for' => 'controller', 'controller' => 'banners')); } } $this->view->checked_zones = $this->request->getPost('zones') ? $this->request->getPost('zones') : array_column($banner->getZones(array('columns' => array('id')))->toArray(), 'id'); $this->view->banner = $banner; $this->view->pick("banners/edit"); $this->view->title = "Редактирование баннера"; \Phalcon\Tag::prependTitle("Редактирование баннера"); } else { $this->dispatcher->forward(array("namespace" => 'App\\Controllers', "controller" => "error", "action" => "notFound")); } }
/** * Работа с валидатором длины строк Phalcon\Validation\Validator\StringLength * * Валидатор, при возможности, использует расширение mb_string, поддерживая работу с разными кодировками * */ /** * Для mb_* функций лучше сразу указать кодирочку, используемую по умолчанию */ mb_internal_encoding("UTF-8"); /** * Работа валидатора идёт через общий объект Phalcon\Validation * */ $validation = new Phalcon\Validation(); /** * Добавление правил валидации осуществляется методом add * * В этом примере добавлен валидатор значения поля name, минимальная длина которого должна быть 5 символов * Так же определено сообщение, которое будет выведено при несоответсвии правилу валидации */ $validation->add('name', new Phalcon\Validation\Validator\StringLength(array('min' => 5, 'messageMinimum' => 'Значение поля name слишком короткое'))); /** * Аналогичный пример, но для проверки на максимальный размер строки в 10 символов */ $validation->add('name2', new Phalcon\Validation\Validator\StringLength(array('max' => 10, 'messageMaximum' => 'Значение поля name2 слишком длинное'))); /** * Можно указывать сразу и минимальную и максимальную длину строки */ $validation->add('name3', new Phalcon\Validation\Validator\StringLength(array('min' => 5, 'max' => 10)));
public function testGetDefaultValidationMessageShouldReturnEmptyStringIfNoneIsSet() { $validation = new \Phalcon\Validation(); $this->assertEmpty($validation->getDefaultMessage('_notexistentvalidationmessage_')); }
public function getAction() { $ans = []; try { if (!$this->request->isGet()) { throw new Exception('请用正确的方式访问我们的API', 99); } $validation = new Phalcon\Validation(); $validation->add('group_id', new Regex(['pattern' => '/[0-9]{0,10}/u', 'message' => 'please give us a number.'])); $validation->add('user_id', new Regex(['pattern' => '/[0-9]{0,10}/u', 'message' => 'please give us a number.'])); $messages = $validation->validate($_GET); foreach ($messages as $message) { throw new Exception($message, 102); } $group_id = $this->request->getQuery('group_id'); $user_id = $this->request->getQuery('user_id'); $group_ids = []; if (is_null($group_id)) { $group_ids = $this->findGroup($user_id); if (is_null($group_ids) || count($group_ids) == 0) { throw new Exception('请提供必要的group_id或user_id', 1103); } } else { $group_ids = []; $group_ids[0] = $group_id; } $conditions = "user_group=" . $group_ids[0]; for ($i = 1; $i < count($group_ids); $i++) { $conditions .= " or user_group=" . $group_ids[$i]; } $items = Item::find($conditions); $data = []; $i = 0; foreach ($items as $item) { $p = []; $p['id'] = $item->id; $p['name'] = $item->name; $p['unit'] = $item->unit; $p['type'] = $item->type; $p['user_group'] = $item->user_group; $data[$i] = $p; $i++; } $ans['data'] = $data; } catch (Exception $e) { $ans['data'] = -1; Utils::makeError($e, $ans); } finally { echo json_encode($ans); } }