I'm using Respect to validate some forms in a project but this project is in Spanish and I don't understand how messages work after spending a long time reading the documentation and even its code.
I'm using Slim and I'm using a NestedValidationException following an example I read on a tutorial on Youtube.
This is the validate method:
public function validate($request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
//In English it's enough with
//$this->errors[$field] = $e->getMessages();
$this->$errors[$field] = $e->getMainMessage();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
I've seen some responses before but some are very hard to grasp for me as I don't intend on doing a whole translation of the library. I'm just attempting to write 5 or 6 custom messages.
EDIT: A method using the messages:
$validation = $this->c->validator->validate($request, [
'username' => v::noWhitespace()->notEmpty()->usernameAvailable(),
'email' => v::noWhitespace()->notEmpty()->email()->emailAvailable(),
'password1' => v::noWhitespace()->notEmpty(),
'password2' => v::noWhitespace()->notEmpty()->identical($inputPassword),
]);
Using findMessages with the parameter you're translating the messages. You just have to replace the content in the catch block:
catch (NestedValidationException $e) {
$errors = $e->findMessages([
'usernameAvailable' => '{{name}} ya existe en la base de datos',
'emailAvailable' => '{{name}} ya existe en la base de datos',
'notEmpty' => '{{name}} no puede estar vacío',
'noWhitespace' => '{{name}} no puede contener espacios',
'email' => '{{name}} debe contener un e-mail válido'
]);
$filteredErrors = array_filter($errors); // Ensure the array is not containing empty values
$this->$errors[$field] = $filteredErrors;
}
Related
In my HunterModel.php file all the validations and custom messages are from the validations, but I don't know if my form_create.php doesn't show the error messages, they simply return to the form without shows the failures committed by the user, why is this happening?
form_create.php
<?php if (isset($validation)) : ?>
<div class="text-danger">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>
<form action="<?= site_url('create')?>" method="POST">
...
</form>
In my HunterController.php method createHunter() must do the record insertion operation, checking if everything is right or returns to the form showing the necessary corrections to the user.
HunterController.php
public function createHunter()
{
try {
helper(['form']);
$hunter = new HunterModel();
$data = [
'name_hunter' => $this->request->getPost('name_hunter'),
'age_hunter' => $this->request->getPost('age_hunter'),
'height_hunter' => $this->request->getPost('height_hunter'),
'weight_hunter' => $this->request->getPost('weight_hunter'),
'type_hunter' => $this->request->getPost('type_hunter'),
'type_nen' => $this->request->getPost('type_nen'),
'type_blood' => $this->request->getPost('type_blood')
];
if ($hunter->insert($data)){
return $this->response->redirect(site_url('listing'));
} else {
$data['validation'] = $this->validator;
echo view('form_create', $data);
}
} catch (\Exception $e) {
exit($e->getMessage());
}
}
HunterModel.php
// Validation
protected $validationRules = [
'nome_hunter' => 'required|max_length[30]',
'idade_hunter' => 'required|integer',
'altura_hunter' => 'required|decimal',
'peso_hunter' => 'required|decimal',
'tipo_hunter' => 'required|max_length[30]',
'tipo_nen' => 'required|max_length[30]',
'tipo_sanguineo' => 'required|max_length[3]'
];
protected $validationMessages = [
'nome_hunter' => [
'required' => 'O nome do Hunter não pode ficar vazio.',
'max_length' => 'O nome do Hunter precisa ter no máximo 30 caracteres.'
],
'idade_hunter' => [
'required' => 'A idade do Hunter não pode ficar vazia.',
'integer' => 'A idade do Hunter precisa ser um número inteiro.'
],
'peso_hunter' => [
'required' => 'O peso do Hunter não pode ficar vazio.',
'decimal' => 'O peso do Hunter precisa ser um número decimal.'
],
'altura_hunter' => [
'required' => 'A altura do Hunter não pode ficar vazia.',
'decimal' => 'A altura do Hunter precisa ser um número decimal.'
],
'tipo_hunter' => [
'required' => 'É necessário definir o tipo de Hunter.',
'max_length' => 'O tipo de Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_nen' => [
'required' => 'É necessário definir o nen do Hunter.',
'max_length' => 'O nen do Hunter precisa ter no máximo 30 caracteres.'
],
'tipo_sanguineo' => [
'required' => 'É necessário definir o tipo sanguíneo do Hunter.',
'max_length' => 'O tipo sanguíneo do Hunter precisa ter no máximo 3 caracteres.'
]
];
you should learning again about validate data,
learn this page
https://codeigniter4.github.io/userguide/libraries/validation.html#form-validation-tutorial
if you want to use helper function, try this
function yourController($request){
helper(['form']);
$validation = \Config\Services::validation();
$rules = [
"nome_hunter" => [
"label" => "nome_hunter",
"rules" => 'required|max_length[30]',
]
];
if ($this->validate($rules)) {
$hunter = new HunterModel();
$hunter->insert($data)
$session = session();
$session->setFlashData("success", "Successful");
return redirect()->to('/');
} else {
$data["validation"] = $validation->getErrors();
}
}
or you can make the validation on your controller, don't make it on model
you can try this too
how to validate form data in codeigniter 4
i want to customize my validation messages using the rules that i set before
public function rules()
{
return [
'cuit' => 'required | numeric | digits:11',
'razon_social' => 'required | alpha | max:64 | min:3',
'fantasia' => 'required | string | max:255 | min:3',
];
}
my messages:
public function messages()
{
return [
'cuit.required' => 'Campo obligatorio',
'cuit.numeric' => 'El CUITsolo puede ser númerico',
'cuit.digits' => 'El CUIT debe tener 11 dígitos',
'razon_social.required' => 'Campo obligatorio',
'razon_social.alpha' => 'La razón social solo puede ser texto',
'razon_social.max' => 'La razón social puede tener hasta 64 caracteres',
'razon_social.min' => 'La razón social debe tener al menos 3 caracteres',
'fantasia.required' => 'Campo obligatorio',
'fantasia.string' => 'El nombre de fantasía solo puede ser texto',
'fantasia.max' => 'Este campo puede tener un maximo de 255 caracteres',
'fantasia.min' => 'Este campo debe tener al menos 3 caracteres',
];
}
}
is there a way to call the rules insted of typing de max min characteers? cus if at somepoint i want to change the rules i will have to change the messages as well.
hope u understand what im trying to do.
I'm trying to include the class that treats the Request from my form, but it always returns error from not found, however, I've already checked and reverted and the file and patch are correct.
I already tried to update the composer to see if it solved, but without success, follow the code below.
Arguments "Class App\Http\Requests\CadastroRequest does not exist"
File CadastroController.php
<?
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB; // Banco de dados
use Request; // Tratamento URI
use Validator; // Validação
use App\Cadastro; // Modelo
use App\Http\Requests\CadastroRequest; // Regras do formulário
class CadastroController extends Controller {
// Formulário de Cadastro
public function cadastro(){
return view('cadastro.formulario');
}
// Registrar Usuário
public function salvar( CadastroRequest $request ){
Cadastro::create( $request->all() );
return redirect('/cadastro/obrigado')->withInput();
}
}
?>
File CadastroRequest.php (root/app/Http/Requests/CadastroRequest.php)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CadastroRequest extends FormRequest {
public function authorize() {
return true; // Manter true para teste
}
public function rules() {
return [
# Informações de contato
'nome' => 'required|min:10',
'email' => 'required|min:10',
'celular' => 'min:11|max:15',
# Informações de acesso
'senha' => 'required|numeric|min:3|max:8',
'rsenha' => 'required|numeric|min:3|max:8',
# Informações de endereço
'estado' => 'required|min:10',
'cidade' => 'required|min:10',
'cep' => 'required|min:10',
'endereco' => 'required|min:10',
'numero' => 'required|min:10',
'bairro' => 'required|min:10',
];
}
public function messages(){
return [
'nome.required' => 'Você precisa informar seu nome.'
'email.required' => 'Insira um e-mail valido, você precisa confirmar o registro.'
'senha.required' => 'Senha é obrigatória.'
'rsenha.required' => 'Confirmação da senha é obrigatória.'
'estado.required' => 'Saber seu estado ajuda a lhe informar jogos acontecendo no seu estado.'
'cidade.required' => 'Saber a cidade que mora ajuda a lhe informar os jogos próximos a você.'
'cep.required' => 'Campo CEP é obrigatório.'
'endereco.required' => 'Campo Endereço é obrigatório.'
'numero.required' => 'Campo Número é obrigatório.'
'bairro.required' => 'Campo Bairro é obrigatório.'
];
}
}
Run this in your terminal :
composer dump-autoload
it will add your class to your project
If it not work, try to add the new request via artisan :
php artisan make:request CadastroRequest
then just copy and paste your code
anybody please give an example of validation form in cakephp, because i have cakephp 2.3.3 and cant' validate forms, doesnt recognize my model Usuario
model usuario
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
};
public $validate = array(
'nombre' => array(
'sololetras' =>array(
'rule' => '/^[a-z]$/i',
'message' => 'Solo se Permite Letras en este Campo'
),
'required'=> true,
'allowEmpty' => false,
),
'apellido' => array(
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'El nombre de usuario debe ser una dirección de email válida.'
),
'allowEmpty' => false,
'required' => true,
),
'nrotlf' => array(
'rule' => array('phone', null, 'us')
)
);
}
?>
UsuarioController
<?php
class UsuariosController extends AppController{
var $name = 'Usuarios';
var $helpers = array('Html','Form');
//var $scaffold;
function cargapaq(){ //Carga la lista de la tabla Paquete
$this->loadModel('Paquete');
$paquetes = $this->Paquete->find('list', array('fields'=>'Paquete.id, Paquete.nombre'));
//debug($paquetes);
$this->set(compact('paquetes'));
}
function cargamod(){ //Carga la lista de la tabla Modelo
$this->loadModel('Modelo');
$modelos = $this->Modelo->find('list', array('fields'=>'Modelo.id, Modelo.nombre'));
//debug($modelos);
$this->set(compact('modelos'));
}
function index(){
$usuarios = $this->Usuario->find('all',array(
'fields'=>array(
'Usuario.nombre',
'Usuario.apellido',
'Usuario.email',
'Usuario.password',
'Usuario.grupo_id',
'Usuario.paquete_id',
'Usuario.modelo_id',
'Usuario.nrotlf',
'Usuario.valido',
'Usuario.id'),
'conditions'=>'Usuario.valido=true',
'order'=>'Usuario.apellido ASC')
);
$this->set('usuarios',$usuarios);
###Carga del nombre de los modelos de telefonos para cada modelo en el index.ctp####
$idmod = Hash::extract($usuarios,'{n}.Usuario.modelo_id');
$array=array();
$modelos=array();
$this->loadModel('Modelo');
for ($i=0; $i < count($idmod); $i++) {
$busqueda = $this->Modelo->find('all', array('fields'=>'Modelo.nombre', 'conditions'=>"Modelo.id=$idmod[$i]"));
array_push($modelos, $busqueda['0']);
}
$this->set('modelos',$modelos);
#######Fin de La Carga#########
###Carga del nombre de los planes de telefonos para cada modelo en el index.ctp####
$idpaq = Hash::extract($usuarios,'{n}.Usuario.paquete_id');
$array=array();
$paquetes=array();
$this->loadModel('Paquete');
for ($i=0; $i < count($idpaq); $i++) {
$busqueda = $this->Paquete->find('all', array('fields'=>'Paquete.nombre', 'conditions'=>"Paquete.id=$idpaq[$i]"));
array_push($paquetes, $busqueda['0']);
}
$this->set('paquetes',$paquetes);
#######Fin de La Carga#########
}
function add(){
if ($this->request->is('post')){
//$this->Usuario->create();
if ($this->Usuario->save($this->request->data)){
$this->Session->SetFlash('Usuario Nuevo Creado');
$this->redirect(array('action'=>'index'),null,true);
}else{
$this->Session->SetFlash('No se ha Agregado el Usuario, intente de Nuevo');
}
}
$this->cargapaq();
$this->cargamod();
}
add.ctp
<?php echo $this->Form->create('Usuario');?>
<fieldset>
<legend>Añadir Nuevo Usuario</legend>
<?php
echo $this->Form->input('nombre');
echo $this->Form->input('apellido');
echo $this->Form->input('email',array('label'=>'Correo Electrónico'));
echo $this->Form->input('password',array('label'=>'Contraseña'));
echo $this->Form->input('password2',array('label'=>'Repita Contraseña', 'type'=>'password'));
echo $this->Form->input('paquete_id',array('label'=>'Plan','empty'=>'(Seleccione un Plan)'));
echo $this->Form->input('modelo_id',array('label'=>'Modelo de Teléfono','empty'=>'(Seleccione un Modelo)'));
echo $this->Form->input('nrotlf',array('label'=>'Numero de Teléfono'));
echo $this->Form->input('grupo_id',array('empty'=>'(Seleccione un Rol)'));
echo $this->Form->input('valido', array('checked'=>'true'));
?>
</fieldset>
<?php echo $this->Form->end('Enviar') ?>
<?php echo $this->Html->link('Mostrar Todos Los Usuarios',array('action'=>'index')); ?>
i've seen the documentation but i can make the validation work
I solved the problem.. was the name of the model and doesnt recongnize the validation
I have a problem in my site created with cakePhp 2.x, when I try to register an account my form check all my rules of my fields and beforeSave crypt the password, but crypt the password before check the password(MatchPassword) with the confirm password and then return me the error tha the two password is't equal because the password is crypt with 40characters.
Here is my Model code, How can I solv this problem?
<?php
//questo modello interessa lòa tabella User
class User extends AppModel{
public $name = 'User'; //non utilizzata nel sito è il nome del modello alla fine per migliorare la compatibilità
public $validate = array(
'password' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
),
'min_lunghezza' => array(
'rule' => array('minLength',5),
'message' => 'La password deve contenere almeno 5 caratteri'
),
'max_lunghezza' => array(
'rule' => array('maxLength',15),
'message' => 'La password deve contenere al massimo 15 caratteri'
),
'password_uguale' => array(
'rule' => 'matchPasswords',
'message' => 'Not equal password'
)
),
'password_confirm' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
)
)
);
public function matchPasswords($data){
if ($data['password']==$this->data['User']['password_confirm']){
return true;
}
$this->invalidate('password_confirm','Le due password non coincidono');
return false;
}
public function beforeSave(){
//crypt
if (isset($this->data['User']['password'])){
$this->data['User']['password']=AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
I had a similar problem -- I'm not sure if it's exactly what you were asking -- but I needed to validate my model, before the beforeSave() rules were applied.
I found CakePHP's Validating Data from the Controller page helpful. Basically, you set the data
$this->ModelName->set($this->request->data);
Then you can check the model's validates() method...
if ($this->ModelName->validates()) { // ...
Then, you can decide whether to save the model or show the user an error using, e.g., $this->Session->setFlash().