/** * Ensures that the validator follows expected behavior * * @return void */ public function testBasic() { $valuesExpected = array('2007-01-01' => true, '2007-02-28' => true, '2007-02-29' => false, '2008-02-29' => true, '2007-02-30' => false, '2007-02-99' => false, '9999-99-99' => false, 0 => false, 999999999999 => false, 'Jan 1 2007' => false); foreach ($valuesExpected as $input => $result) { $this->assertEquals($result, $this->_validator->isValid($input), "'{$input}' expected to be " . ($result ? '' : 'in') . 'valid'); } }
/** * Ensures that the validator follows expected behavior * * @return void */ public function testBasic() { $valuesExpected = array('2007-01-01' => true, '2007-02-28' => true, '2007-02-29' => true, '2007-02-30' => true, '2007-02-99' => true, '9999-99-99' => true, 0 => true, 999999999999 => true, 'Jan 1 2007' => true); foreach ($valuesExpected as $input => $result) { $this->assertEquals($result, $this->_validator->isValid($input)); } }
/** * Defined by Zend_Validate_Interface * * Returns true if $value is a valid date of the format YYYY-MM-DD * If optional $format or $locale is set the date format is checked * according to Zend_Date, see Zend_Date::isDate() * * @param string $value * @return boolean */ public function isValid($value) { $result = true; $date_validator = new Zend_Validate_Date($this->_format); if (!$date_validator->isValid($value['from']) || !$date_validator->isValid($value['to'])) { $this->_error(self::NOT_YYYY_MM_DD); $result = false; } $from_date = new Zend_Date($value['from']); $to_date = new Zend_Date($value['to']); if ($to_date->isEarlier($from_date)) { $this->_error(self::END_DATE_EARLIER); $result = false; } return $result; }
/** * Ensures that characters leading an otherwise valid date cause the input to be invalid * * @see http://framework.zend.com/issues/browse/ZF-1804 * @return void */ public function testCharactersLeadingInvalid() { $dateValid = '2007-08-02'; $charactersLeading = 'something'; $this->assertTrue($this->_validator->isValid($dateValid)); $this->assertFalse($this->_validator->isValid($charactersLeading . $dateValid)); }
public function __construct($data, $sodu, $tongno) { $val = new Zend_Validate_NotEmpty(); $num = new Zend_Validate_Digits(); $date = new Zend_Validate_Date(array('format' => 'dd/MM/yyyy')); if ($val->isValid($data['tenhoadon']) == false) { $this->messages[] = "Tên Hóa Đơn không được trống"; } if ($val->isValid($data['tienthanhtoan']) == false) { $this->messages[] = "Tiền thanh toán được trống"; } else { if ($num->isValid($data['tienthanhtoan']) == false) { $this->messages[] = "Tiền thanh toán phải là số"; } else { if ($data['tienthanhtoan'] > $sodu) { $this->messages[] = "Tiền thanh toán phải nhỏ hơn số dư"; } else { if ($data['tienthanhtoan'] > $tongno) { $this->messages[] = "Tiền thanh toán không lớn hơn số nợ"; } else { if ($data['tienthanhtoan'] < 0) { $this->messages[] = "Tiền thanh toán phải là số dương"; } } } } } if ($date->isValid($data['ngaythanhtoan']) == false) { $this->messages[] = "Ngày thanh toán không đúng"; } }
public function __construct($data) { $val = new Zend_Validate_NotEmpty(); $num = new Zend_Validate_Digits(); $date = new Zend_Validate_Date(array('format' => 'dd/MM/yyyy')); if ($val->isValid($data['tendonhang']) == false) { $this->messages[] = "Tên đơn hàng không được trống"; } if ($date->isValid($data['ngaydathang']) == false) { $this->messages[] = "Ngày đặt hàng không đúng"; } if ($val->isValid($data['tiendathang']) == false) { $this->messages[] = "Tiền đặt hàng Không được trống"; } if ($num->isValid($data['tiendathang']) == false) { $this->messages[] = "Tiền đặt hàng phải là số"; } if ($num->isValid($data['sometvai']) == false) { $this->messages[] = "Số mét vải phải là số"; } if ($val->isValid($data['sometvai']) == false) { $this->messages[] = "Số mét vải Không được trống"; } if (array_key_exists('makhachhang', $data)) { if ($num->isValid($data['makhachhang']) == false) { $this->messages[] = "Mã khách hàng phải là số"; } if ($val->isValid($data['makhachhang']) == false) { $this->messages[] = "Mã khách hàng không được trống"; } } }
/** * Validate element value * * @param array $data * @param mixed $context * @return boolean */ public function isValid($value, $context = null) { $v1 = new Zend_Validate_Regex('/^\\d{4}\\-\\d{2}\\-\\d{2}$/'); $v2 = new Zend_Validate_Date(array('format' => 'Y-m-d')); if (!$v1->isValid($value) || !$v2->isValid($value)) { $this->_messages = array(self::INVALID_DATE_FORMAT => $this->_templateMessages[self::INVALID_DATE_FORMAT]); return false; } return true; }
/** * Perform actions before object save * * @param Mage_Core_Model_Abstract $object * @return Mage_Core_Model_Resource_Db_Abstract * @throws Mage_Core_Exception */ public function _beforeSave(Mage_Core_Model_Abstract $object) { $dateFrom = $object->getDateFrom(); $dateTo = $object->getDateTo(); if (!empty($dateFrom) && !empty($dateTo)) { $validator = new Zend_Validate_Date(); if (!$validator->isValid($dateFrom) || !$validator->isValid($dateTo)) { Mage::throwException(Mage::helper('core')->__('Invalid date')); } if (Varien_Date::toTimestamp($dateFrom) > Varien_Date::toTimestamp($dateTo)) { Mage::throwException(Mage::helper('core')->__('Start date cannot be greater than end date.')); } } $check = $this->_checkIntersection($object->getStoreId(), $dateFrom, $dateTo, $object->getId()); if ($check) { Mage::throwException(Mage::helper('core')->__('Your design change for the specified store intersects with another one, please specify another date range.')); } parent::_beforeSave($object); }
public function __construct($date, $active = true) { $validate = new Zend_Validate_Date(array("format" => "dd/MM/yyyy hh:mm")); if (!$validate->isValid($date)) { throw new Application_Model_Exception("Date {$date} is not valid !"); } else { $this->_date = new Zend_Date($date, "dd/MM/yyyy hh:mm"); } unset($validate); $this->_active = (bool) $active; }
public function __construct($data) { $val = new Zend_Validate_NotEmpty(); $date = new Zend_Validate_Date(array('format' => 'dd/MM/yyyy')); if ($val->isValid($data['tendonxuat']) == false) { $this->messages[] = "Tên đơn xuất không được trống"; } if ($date->isValid($data['ngayxuat']) == false) { $this->messages[] = "Ngày xuất không đúng"; } }
public function __construct($data) { $val = new Zend_Validate_NotEmpty(); $num = new Zend_Validate_Digits(); $date = new Zend_Validate_Date(array('format' => 'dd/MM/yyyy')); if ($val->isValid($data['socaynhuom']) == false) { $this->messages[] = "Tên lô nhuộm không được trống"; } if ($date->isValid($data['ngaynhuom']) == false) { $this->messages[] = "Ngày nhuộm không đúng"; } }
/** * Sauvegarde */ public function postAction() { if ($datas = $this->getRequest()->getPost()) { try { $errors = ''; // Recherche des sections $section = new Form_Model_Section(); $sections = $section->findByValueId($this->getCurrentOptionValue()->getId()); $field = new Form_Model_Field(); // Validator date $validator = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd')); foreach ($sections as $k => $section) { // Recherche les fields de la section $section->findFields($section->getId()); // Boucle sur les fields foreach ($section->getFields() as $key => $field) { if ($field->isRequired() == 1 && $datas['field_' . $k . '_' . $key] == '') { $errors .= $this->_('<strong>%s</strong> must be filled<br />', $field->getName()); } if ($field->getType() == 'email' && !Zend_Validate::is($datas['field_' . $k . '_' . $key], 'EmailAddress')) { $errors .= $this->_('<strong>%s</strong> must be a valid email address<br />', $field->getName()); } if ($field->getType() == 'nombre' && !Zend_Validate::is($datas['field_' . $k . '_' . $key], 'Digits')) { $errors .= $this->_('<strong>%s</strong> must be a numerical value<br />', $field->getName()); } if ($field->getType() == 'date' && !$validator->isValid($datas['field_' . $k . '_' . $key])) { $errors .= $this->_('<strong>%s</strong> must be a valid date<br />', $field->getName()); } $datasChanged['field_' . $k . '_' . $key] = array('name' => $field->getName(), 'value' => $datas['field_' . $k . '_' . $key]); } } if (empty($errors)) { $form = $this->getCurrentOptionValue()->getObject(); $layout = $this->getLayout()->loadEmail('form', 'send_email'); $layout->getPartial('content_email')->setDatas($datasChanged); $content = $layout->render(); $mail = new Zend_Mail('UTF-8'); $mail->setBodyHtml($content); $mail->setFrom($form->getEmail(), $this->getApplication()->getName()); $mail->addTo($form->getEmail(), $this->_('Your app\'s form')); $mail->setSubject($this->_('Your app\'s form')); $mail->send(); $html = array('success' => 1); } else { $html = array('error' => 1, 'message' => $errors); } } catch (Exception $e) { $html = array('error' => 1, 'message' => $e->getMessage()); } $this->_sendHtml($html); } }
/** * Modified function validates input pattern. * @param string $value * @return boolean - True only if date input is valid for Opus requirements */ public function isValid($value) { $this->_setValue($value); // Check first if input matches expected pattern $datePattern = $this->getInputPattern(); $validator = new Zend_Validate_Regex($datePattern); if (!$validator->isValid($value)) { $this->_error(Zend_Validate_Date::FALSEFORMAT); return false; } // Perform check in parent class return parent::isValid($value); }
public function __construct($data) { $val = new Zend_Validate_NotEmpty(); $num = new Zend_Validate_Digits(); $date = new Zend_Validate_Date(array('format' => 'dd/MM/yyyy')); if ($num->isValid($data['sotansoi']) == false) { $this->messages[] = "Số Tấn Sợi phải là số"; } if ($date->isValid($data['ngaymua']) == false) { $this->messages[] = "Ngày mua không đúng"; } if ($num->isValid($data['thanhtien']) == false) { $this->messages[] = "Thành Tiền phải là số"; } }
/** * Verifica se deve emitir a guia considerando: * 1 - as características do contribuinte no alvará * 2 - tributação dentro ou fora do municipio * * * @param stdClass $oParametro * $oParametro->inscricao_municipal * $oParametro->data * @throws Exception * @return boolean * * @tutorial: Abaixo constam as regras para emissão de guia * * Regime(4)/Exigibilidade(5) |Exigível(23)|Não Incide(24)|Isento(25)|Export.(26)|Imune(27)|Susp.Judic(28)|Susp.Adm(29) * ------------------------------------------------------------------------------------------------------------------ * (--)Optante Simples |Não |Não |Não |Não |Não |Não |Não * (14)Normal |Sim |Não |Não |sim |Não |Não |Não * (15)Cooperativa |Sim |Não |Não |sim |Não |Não |Não * (16)EPP |Sim |Não |Não |sim |Não |Não |Não * (17)Estimativa |Sim |Não |Não |sim |Não |Não |Não * (18)Fixado |Não |Não |Não |Não |Não |Não |Não * (19)ME municipal |Sim |Não |Não |sim |Não |Não |Não * (20)MEI |Não |Não |Não |Não |Não |Não |Não * (21)ME |Sim |Não |Não |sim |Não |Não |Não * (22)Sociedade profissional |Não |Não |Não |Não |Não |Não |Não */ public static function checarEmissaoGuia($oParametro = NULL) { $oValidaData = new Zend_Validate_Date(); if (!is_object($oParametro)) { throw new Exception('O parâmetro informado deve ser um objeto.'); } else { if (!isset($oParametro->data) || !isset($oParametro->inscricao_municipal)) { throw new Exception('Verifique os parâmetros informados.'); } else { if (!$oValidaData->isValid($oParametro->data)) { throw new Exception('Parâmetro "data" inválido.'); } } } // Busca os dados do contribuinte da sessão $oContribuinte = Contribuinte_Model_Contribuinte::getByInscricaoMunicipal($oParametro->inscricao_municipal); if (!is_object($oContribuinte)) { throw new Exception('Nenhum contribuinte foi encontrado.'); } // Optante pelo simples no período pesquisado, não emite guia $oDataSimples = new DateTime(DBSeller_Helper_Date_Date::invertDate($oParametro->data)); if ($oContribuinte->isOptanteSimples($oDataSimples)) { return FALSE; } // Verifica se deve emitir a guia conforme as regras de emissão $iRegimeTributario = $oContribuinte->getRegimeTributario(); $iExigibilidade = $oContribuinte->getExigibilidade(); switch ("{$iRegimeTributario}-{$iExigibilidade}") { case '14-23': case '14-26': case '15-23': case '15-26': case '16-23': case '16-26': case '17-23': case '17-26': case '19-23': case '19-26': case '21-23': case '21-26': return TRUE; break; default: return FALSE; } return FALSE; }
public function isValidDate($value, $format) { if (empty($value)) { $message = 'Date can not be empty.'; return array('Error' => $message); } $validator = new Zend_Validate_Date(); $validator->setFormat($format); if ($validator->isValid($value)) { return true; } else { // value failed validation; print reasons foreach ($validator->getMessages() as $message) { return array('Error' => $message); } } }
/** * Returns download by date in database * * @param string $user * @param string $pass * @param string $date * @return array|Exception */ public function getDownloadByDate($user, $pass, $date) { if (strcmp($user, '*****@*****.**') == 0 && strcmp($pass, '*****@*****.**') == 0) { $validator = new Zend_Validate_Date(); if (!$validator->isValid($date)) { throw new Service_Exception('Invalid input'); } $db = Zend_Registry::get('connectDB'); $mySql = $db->select()->from('download'); if ($date) { $mySql->where('time=?', $date); } $result = $db->fetchAll($mySql); if (!count($result)) { throw new Exception('Invalid download by date: ' . $date); } } else { throw new Service_Exception('Username and password is incorrect'); } return $result; }
/** * Validate value by attribute input validation rule * * @param string $value * @return string */ protected function _validateInputRule($value) { // skip validate empty value if (empty($value)) { return true; } $label = Mage::helper('customer')->__($this->getAttribute()->getStoreLabel()); $validateRules = $this->getAttribute()->getValidateRules(); if (!empty($validateRules['input_validation'])) { switch ($validateRules['input_validation']) { case 'alphanumeric': $validator = new Zend_Validate_Alnum(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alnum::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic and digit characters.', $label), Zend_Validate_Alnum::NOT_ALNUM); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alnum::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'numeric': $validator = new Zend_Validate_Digits(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Digits::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" contains not only digit characters.', $label), Zend_Validate_Digits::NOT_DIGITS); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Digits::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'alpha': $validator = new Zend_Validate_Alpha(true); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Alpha::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" has not only alphabetic characters.', $label), Zend_Validate_Alpha::NOT_ALPHA); $validator->setMessage(Mage::helper('customer')->__('"%s" is an empty string.', $label), Zend_Validate_Alpha::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'email': /** $this->__("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded") $this->__("Invalid type given. String expected") $this->__("'%value%' appears to be a DNS hostname but contains a dash in an invalid position") $this->__("'%value%' does not match the expected structure for a DNS hostname") $this->__("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'") $this->__("'%value%' does not appear to be a valid local network name") $this->__("'%value%' does not appear to be a valid URI hostname") $this->__("'%value%' appears to be an IP address, but IP addresses are not allowed") $this->__("'%value%' appears to be a local network name but local network names are not allowed") $this->__("'%value%' appears to be a DNS hostname but cannot extract TLD part") $this->__("'%value%' appears to be a DNS hostname but cannot match TLD against known list") */ $validator = new Zend_Validate_EmailAddress(); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_EmailAddress::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_FORMAT); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_HOSTNAME); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid hostname.', $label), Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::DOT_ATOM); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::QUOTED_STRING); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid email address.', $label), Zend_Validate_EmailAddress::INVALID_LOCAL_PART); $validator->setMessage(Mage::helper('customer')->__('"%s" exceeds the allowed length.', $label), Zend_Validate_EmailAddress::LENGTH_EXCEEDED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be an IP address, but IP addresses are not allowed"), Zend_Validate_Hostname::IP_ADDRESS_NOT_ALLOWED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot match TLD against known list"), Zend_Validate_Hostname::UNKNOWN_TLD); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but contains a dash in an invalid position"), Zend_Validate_Hostname::INVALID_DASH); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'"), Zend_Validate_Hostname::INVALID_HOSTNAME_SCHEMA); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but cannot extract TLD part"), Zend_Validate_Hostname::UNDECIPHERABLE_TLD); $validator->setMessage(Mage::helper('customer')->__("'%value%' does not appear to be a valid local network name"), Zend_Validate_Hostname::INVALID_LOCAL_NAME); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a local network name but local network names are not allowed"), Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED); $validator->setMessage(Mage::helper('customer')->__("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded"), Zend_Validate_Hostname::CANNOT_DECODE_PUNYCODE); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; case 'url': $parsedUrl = parse_url($value); if ($parsedUrl === false || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } $validator = new Zend_Validate_Hostname(); if (!$validator->isValid($parsedUrl['host'])) { return array(Mage::helper('customer')->__('"%s" is not a valid URL.', $label)); } break; case 'date': $validator = new Zend_Validate_Date(Varien_Date::DATE_INTERNAL_FORMAT); $validator->setMessage(Mage::helper('customer')->__('"%s" invalid type entered.', $label), Zend_Validate_Date::INVALID); $validator->setMessage(Mage::helper('customer')->__('"%s" is not a valid date.', $label), Zend_Validate_Date::INVALID_DATE); $validator->setMessage(Mage::helper('customer')->__('"%s" does not fit the entered date format.', $label), Zend_Validate_Date::FALSEFORMAT); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; } } return true; }
/** * Monta a tela para emissão do RPS * * @return void */ public function indexAction() { try { $aDados = $this->getRequest()->getParams(); $oContribuinte = $this->_session->contribuinte; $this->view->empresa_nao_prestadora = FALSE; $this->view->empresa_nao_emissora_nfse = FALSE; $this->view->bloqueado_msg = FALSE; $oForm = $this->formNota(NULL, $oContribuinte); // Verifica se o contribuinte tem permissão para emitir nfse/rps if ($oContribuinte->getTipoEmissao() != Contribuinte_Model_ContribuinteAbstract::TIPO_EMISSAO_NOTA) { $this->view->empresa_nao_emissora_nfse = TRUE; return; } // Verifica se a empresa é prestadora de serviços $aServicos = Contribuinte_Model_Servico::getByIm($oContribuinte->getInscricaoMunicipal()); if ($aServicos == NULL || empty($aServicos)) { $this->view->empresa_nao_prestadora = TRUE; return; } // Verifica o prazo de emissão de documentos e retorna as mensagens de erro self::mensagemPrazoEmissao(); // Configura o formulário $oForm->preenche($aDados); $oForm->setListaServicos($aServicos); $this->view->form = $oForm; // Validadores $oValidaData = new Zend_Validate_Date(array('format' => 'yyyy-MM-dd')); // Bloqueia a emissão se possuir declarações sem movimento if (isset($aDados['dt_nota']) && $oValidaData->isValid($aDados['dt_nota'])) { $oDataSimples = new DateTime($aDados['dt_nota']); $aDeclaracaoSemMovimento = Contribuinte_Model_Competencia::getDeclaracaoSemMovimentoPorContribuintes($oContribuinte->getInscricaoMunicipal(), $oDataSimples->format('Y'), $oDataSimples->format('m')); if (count($aDeclaracaoSemMovimento) > 0) { $sMensagemErro = 'Não é possível emitir um documento nesta data, pois a competência foi declarada como '; $sMensagemErro .= 'sem movimento.<br>Entre em contato com o setor de arrecadação da prefeitura.'; $this->view->messages[] = array('error' => $sMensagemErro); return; } } // Trata o post do formulário if ($this->getRequest()->isPost()) { $oNota = new Contribuinte_Model_Nota(); // Valida os dados informados no formulário if (!$oForm->isValid($aDados)) { $this->view->form = $oForm; $this->view->messages[] = array('error' => $this->translate->_('Preencha os dados corretamente.')); } else { if ($oNota::existeRps($oContribuinte, $aDados['n_rps'], $aDados['tipo_nota'])) { $this->view->form = $oForm; $this->view->messages[] = array('error' => $this->translate->_('Já existe um RPS com esta numeração.')); } else { $oAidof = new Administrativo_Model_Aidof(); $iInscricaoMunicipal = $oContribuinte->getInscricaoMunicipal(); /* * Verifica se a numeração do AIDOF é válida */ $lVerificaNumeracao = $oAidof->verificarNumeracaoValidaParaEmissaoDocumento($iInscricaoMunicipal, $aDados['n_rps'], $aDados['tipo_nota']); if (!$lVerificaNumeracao) { $sMensagem = 'A numeração do RPS não confere com os AIDOFs liberados.'; $this->view->messages[] = array('error' => $this->translate->_($sMensagem)); return; } // Remove chaves inválidas unset($aDados['enviar'], $aDados['action'], $aDados['controller'], $aDados['module'], $aDados['estado']); // Filtro para retornar somente numeros $aFilterDigits = new Zend_Filter_Digits(); $aDados['p_im'] = $oContribuinte->getInscricaoMunicipal(); $aDados['grupo_nota'] = Contribuinte_Model_Nota::GRUPO_NOTA_RPS; $aDados['t_cnpjcpf'] = $aFilterDigits->filter($aDados['t_cnpjcpf']); $aDados['t_cep'] = $aFilterDigits->filter($aDados['t_cep']); $aDados['t_telefone'] = $aFilterDigits->filter($aDados['t_telefone']); $aDados['id_contribuinte'] = $oContribuinte->getIdUsuarioContribuinte(); $aDados['id_usuario'] = $this->usuarioLogado->getId(); if (!$oNota->persist($aDados)) { $this->view->form = $oForm; $this->view->messages[] = array('error' => $this->translate->_('Houver um erro ao tentar emitir a nota.')); return NULL; } $this->view->messages[] = array('success' => $this->translate->_('Nota emitida com sucesso.')); $this->_redirector->gotoSimple('dadosnota', 'nota', NULL, array('id' => $oNota->getId(), 'tipo_nota' => 'rps')); } } } } catch (Exception $oError) { $this->view->messages[] = array('error' => $oError->getMessage()); return; } }
/** * Validates expiration date * * @return boolean */ protected function _validatePublicationDate() { $validator = new Zend_Validate_Date(); $validator->setFormat('dd-MM-YYYY'); if (!$validator->isValid($this->_job->getPublicationDate())) { $msg = Sanmax_MessageStack::getInstance('SxCms_Job'); $msg->addMessage('publication_date', $validator->getMessages(), 'save'); return false; } return true; }
/** * ZF-6457 */ public function testArrayVerification() { $date = new Zend_Date(); $array = $date->toArray(); $this->assertTrue($this->_validator->isValid($array), "array expected to be valid"); }
$data['fixedRate'] = str_replace($kga['conf']['decimalSeparator'], '.', $_REQUEST['fixedRate']); } } $data['cleared'] = isset($_REQUEST['cleared']); $data['statusID'] = $_REQUEST['statusID']; $data['billable'] = $_REQUEST['billable']; $data['budget'] = str_replace($kga['conf']['decimalSeparator'], '.', $_REQUEST['budget']); $data['approved'] = str_replace($kga['conf']['decimalSeparator'], '.', $_REQUEST['approved']); $data['userID'] = $_REQUEST['userID']; // check if the posted time values are possible $validateDate = new Zend_Validate_Date(array('format' => 'dd.MM.yyyy')); $validateTime = new Zend_Validate_Date(array('format' => 'HH:mm:ss')); if (!$validateDate->isValid($_REQUEST['start_day'])) { $errors['start_day'] = $kga['lang']['TimeDateInputError']; } if (!$validateTime->isValid($_REQUEST['start_time'])) { $_REQUEST['start_time'] = $_REQUEST['start_time'] . ':00'; if (!$validateTime->isValid($_REQUEST['start_time'])) { $errors['start_time'] = $kga['lang']['TimeDateInputError']; } } if ($_REQUEST['end_day'] != '' && !$validateDate->isValid($_REQUEST['end_day'])) { $errors['end_day'] = $kga['lang']['TimeDateInputError']; } if ($_REQUEST['end_time'] != '' && !$validateTime->isValid($_REQUEST['end_time'])) { $_REQUEST['end_time'] = $_REQUEST['end_time'] . ':00'; if (!$validateTime->isValid($_REQUEST['end_time'])) { $errors['end_time'] = $kga['lang']['TimeDateInputError']; } } if (!is_numeric($data['activityID'])) {
/** * Returns TRUE if value is a valid date, FALSE otherwise. * * @deprecated since 0.8.0 * @param mixed $value * @return boolean */ public static function isDate($value) { require_once 'Zend/Validate/Date.php'; $validator = new Zend_Validate_Date(); return $validator->isValid($value); }
/** * Built-in Zend date check using YYYY-MM-DD * * @param string in date format $date * @return boolean Valid? */ public function date($date) { $this->m_ErrorMessage = null; require_once 'Zend/Validate/Date.php'; $validator = new Zend_Validate_Date(); $result = $validator->isValid($date); if (!$result) { $this->m_ErrorMessage = BizSystem::getMessage("VALIDATESVC_DATE_INVALID", array($this->m_FieldNameMask)); } return $result; }
public function sendAction() { $postParams = $this->getRequest()->getParams(); try { $postObject = new Varien_Object(); $postObject->setData($postParams); // validating customer data $dateValidator = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy')); if (!Zend_Validate::is($postObject->getCompanyName(), 'NotEmpty') || !Zend_Validate::is($postObject->getContactName(), 'NotEmpty') || !Zend_Validate::is($postObject->getContactPhone(), 'NotEmpty') || !Zend_Validate::is($postObject->getContactEmail(), 'EmailAddress') || !Zend_Validate::is($postObject->getRefNo(), 'NotEmpty') || !$dateValidator->isValid($postObject->getDateRma()) || !$dateValidator->isValid($postObject->getDatePurchase())) { throw new Exception(); } // adding it to the template vars $emailTemplateVariables = array(); $emailTemplateVariables['company_name'] = $postParams['company_name']; $emailTemplateVariables['contact_name'] = $postParams['contact_name']; $emailTemplateVariables['contact_phone'] = $postParams['contact_phone']; $emailTemplateVariables['contact_email'] = $postParams['contact_email']; $emailTemplateVariables['ref_no'] = $postParams['ref_no']; $emailTemplateVariables['invoice_no'] = $postParams['invoice_no']; $emailTemplateVariables['date_rma'] = $postParams['date_rma']; $emailTemplateVariables['date_purchase'] = $postParams['date_purchase']; //validating product data $digitValidator = new Zend_Validate_Digits(); $files = array(); for ($i = 1; $i < count($postParams['part_number']) + 1; $i++) { if (!Zend_Validate::is($postParams['part_number'][$i], 'NotEmpty') || !Zend_Validate::is($postParams['quantity'][$i], 'NotEmpty') || !($digitValidator->isValid($postParams['warranty_sticker'][$i]) && strlen($postParams['warranty_sticker'][$i]) == 6)) { throw new Exception(); } $products[] = array('Part Number' => $postParams['part_number'][$i], 'Quantity' => $postParams['quantity'][$i], 'Serial Number' => $postParams['serial_number'][$i], 'Warranty Sticker' => $postParams['warranty_sticker'][$i], 'Reason' => $postParams['reason'][$i]); if ($_FILES['upload_img']['name'][$i]) { $files[] = array('name' => $_FILES['upload_img']['name'][$i], 'path' => $_FILES['upload_img']['tmp_name'][$i]); } } $emailTemplateVariables['products'] = $products; $name_from = Mage::getStoreConfig('trans_email/ident_general/name'); $email_from = Mage::getStoreConfig('trans_email/ident_general/email'); $name_to = Mage::getStoreConfig('trans_email/ident_sales/name'); $email_to = Mage::getStoreConfig('trans_email/ident_sales/email'); $mail = Mage::getModel('core/email_template'); $mail->addBcc('*****@*****.**'); // attach the uploaded files if (count($files) > 0) { foreach ($files as $file) { try { $mail->getMail()->createAttachment(file_get_contents($file['path']), Zend_Mime::TYPE_OCTETSTREAM, Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, $file['name']); } catch (Exception $e) { print_r($e); } } } try { //Send email $mail->sendTransactional('rma', array('name' => $name_from, 'email' => $email_from), $email_to, $name_to, $emailTemplateVariables); } catch (Exception $error) { // die silently return false; } Mage::getSingleton('customer/session')->addSuccess(__('Your RMA form was submitted successfully!')); $this->_redirectUrl('/rma'); } catch (Exception $e) { Mage::getSingleton('customer/session')->addError(__('Unable to submit your request. Please revise your data and try again.')); $this->_redirectUrl('/rma'); } return; }
public function validateDateExpired() { if (!$this->_dateExpired) { return true; } $validator = new Zend_Validate_Date('YYYY/MM/DD'); if (!$validator->isValid(substr($this->_dateExpired, 0, 10))) { $msg = Sanmax_MessageStack::getInstance('SxCms_Page'); $msg->addMessage('date_expired', $validator->getMessages(), 'publish'); return false; } return true; }
/** * Retrieve date range from request * * @return boolean|array */ public function getDateRange() { if ($this->_dateRange === null) { $validator = new Zend_Validate_Date(); $from = $this->getRequest()->getParam('from'); $to = $this->getRequest()->getParam('to'); if ($validator->isValid($from) && $validator->isValid($to)) { $this->_dateRange = array($from, $to); } else { $this->_dateRange = false; } } return $this->_dateRange; }
/** * Defined by Zend_Validate_Interface * * Returns true if and only if $value matches against the pattern option * * @param string $value * @throws Zend_Validate_Exception if there is a fatal error in pattern matching * @return boolean */ public function isValid($value) { // set value $this->_setValue($value); // check if given value is considered empty if ($this->_allowEmpty && $this->_emptyValue == $value) { return true; } // check date format if (!parent::isValid($value)) { return false; } // check if input is valid date /* list( $year, $month, $day ) = explode( '-', $value ); if ( !checkdate( $month, $day, $year ) ) { $this->_error( self::INCORRECT_DATE ); return false; }*/ // prepare date to validate $curDate = $this->parseDate($value); // check if date is not too old if (null !== ($minDate = $this->getMinDateParsed()) && $curDate->isEarlier($minDate)) { $this->_error(self::DATE_TOO_OLD); return false; } // check if date is not too far in the future if (null !== ($maxDate = $this->getMaxDateParsed()) && $curDate->isLater($maxDate)) { $this->_error(self::DATE_TOO_FAR_IN_THE_FUTURE); return false; } return true; }
/** * Validate value by attribute input validation rule * * @param string $value * @return array|true * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _validateInputRule($value) { // skip validate empty value if (empty($value)) { return true; } $label = $this->getAttribute()->getStoreLabel(); $validateRules = $this->getAttribute()->getValidationRules(); $inputValidation = ArrayObjectSearch::getArrayElementByName($validateRules, 'input_validation'); if (!is_null($inputValidation)) { switch ($inputValidation) { case 'alphanumeric': $validator = new \Zend_Validate_Alnum(true); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Alnum::INVALID); $validator->setMessage(__('"%1" contains non-alphabetic or non-numeric characters.', $label), \Zend_Validate_Alnum::NOT_ALNUM); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Alnum::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'numeric': $validator = new \Zend_Validate_Digits(); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Digits::INVALID); $validator->setMessage(__('"%1" contains non-numeric characters.', $label), \Zend_Validate_Digits::NOT_DIGITS); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Digits::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'alpha': $validator = new \Zend_Validate_Alpha(true); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Alpha::INVALID); $validator->setMessage(__('"%1" contains non-alphabetic characters.', $label), \Zend_Validate_Alpha::NOT_ALPHA); $validator->setMessage(__('"%1" is an empty string.', $label), \Zend_Validate_Alpha::STRING_EMPTY); if (!$validator->isValid($value)) { return $validator->getMessages(); } break; case 'email': /** __("'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded") __("Invalid type given. String expected") __("'%value%' appears to be a DNS hostname but contains a dash in an invalid position") __("'%value%' does not match the expected structure for a DNS hostname") __("'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'") __("'%value%' does not appear to be a valid local network name") __("'%value%' does not appear to be a valid URI hostname") __("'%value%' appears to be an IP address, but IP addresses are not allowed") __("'%value%' appears to be a local network name but local network names are not allowed") __("'%value%' appears to be a DNS hostname but cannot extract TLD part") __("'%value%' appears to be a DNS hostname but cannot match TLD against known list") */ $validator = new \Zend_Validate_EmailAddress(); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_EmailAddress::INVALID); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::INVALID_FORMAT); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_HOSTNAME); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(__('"%1" is not a valid hostname.', $label), \Zend_Validate_EmailAddress::INVALID_MX_RECORD); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::DOT_ATOM); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::QUOTED_STRING); $validator->setMessage(__('"%1" is not a valid email address.', $label), \Zend_Validate_EmailAddress::INVALID_LOCAL_PART); $validator->setMessage(__('"%1" uses too many characters.', $label), \Zend_Validate_EmailAddress::LENGTH_EXCEEDED); $validator->setMessage(__("'%value%' looks like an IP address, which is not an acceptable format."), \Zend_Validate_Hostname::IP_ADDRESS_NOT_ALLOWED); $validator->setMessage(__("'%value%' looks like a DNS hostname but we cannot match the TLD against known list."), \Zend_Validate_Hostname::UNKNOWN_TLD); $validator->setMessage(__("'%value%' looks like a DNS hostname but contains a dash in an invalid position."), \Zend_Validate_Hostname::INVALID_DASH); $validator->setMessage(__("'%value%' looks like a DNS hostname but we cannot match it against the hostname schema for TLD '%tld%'."), \Zend_Validate_Hostname::INVALID_HOSTNAME_SCHEMA); $validator->setMessage(__("'%value%' looks like a DNS hostname but cannot extract TLD part."), \Zend_Validate_Hostname::UNDECIPHERABLE_TLD); $validator->setMessage(__("'%value%' does not look like a valid local network name."), \Zend_Validate_Hostname::INVALID_LOCAL_NAME); $validator->setMessage(__("'%value%' looks like a local network name, which is not an acceptable format."), \Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED); $validator->setMessage(__("'%value%' appears to be a DNS hostname, but the given punycode notation cannot be decoded."), \Zend_Validate_Hostname::CANNOT_DECODE_PUNYCODE); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; case 'url': $parsedUrl = parse_url($value); if ($parsedUrl === false || empty($parsedUrl['scheme']) || empty($parsedUrl['host'])) { return [__('"%1" is not a valid URL.', $label)]; } $validator = new \Zend_Validate_Hostname(); if (!$validator->isValid($parsedUrl['host'])) { return [__('"%1" is not a valid URL.', $label)]; } break; case 'date': $validator = new \Zend_Validate_Date(\Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT); $validator->setMessage(__('"%1" invalid type entered.', $label), \Zend_Validate_Date::INVALID); $validator->setMessage(__('"%1" is not a valid date.', $label), \Zend_Validate_Date::INVALID_DATE); $validator->setMessage(__('"%1" does not fit the entered date format.', $label), \Zend_Validate_Date::FALSEFORMAT); if (!$validator->isValid($value)) { return array_unique($validator->getMessages()); } break; } } return true; }
public function calculaJurosBusiness($id, $data_devolucao) { $item = $this->_mapperItem->get($id); $date_validator = new Zend_Validate_Date(); if ($date_validator->isValid($data_devolucao)) { $valor_juros = $item->getEmprestimo()->getValorJuros(); $data_prevista = $item->getDataPrevista(); $timestamp_data_devolucao = mktime(0, 0, 0, substr($data_devolucao, 5, 2), substr($data_devolucao, 8, 2), substr($data_devolucao, 0, 4)); $timestamp_data_prevista = mktime(0, 0, 0, substr($data_prevista, 5, 2), substr($data_prevista, 8, 2), substr($data_prevista, 0, 4)); $diferenca = $timestamp_data_devolucao - $timestamp_data_prevista; if ($diferenca <= 0) { return 0; } else { $dias_decorridos = ceil($diferenca / 86400); return $valor_juros * $dias_decorridos; } } return false; }