Laravel server side form validation, Validate field length(Size) with more than one option - laravel-5

I'm using ajax to make a server side form validation in laravel. All my validations are working fine except for one which i can figure out how to do it. Actually i have a field in my form for the ID number, which can take either 7 caracters for passport number, 9 caracters for ID card number or 20 caracters for temporary ID card number. How can i set a validation for size or lenght with 3 differents options?
function validation(e, f) {
var x = document.getElementsByClassName("alert-danger");
var y = "false";
var i;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/membre/modalValidation",
method: "post",
data: (e == 1) ? new FormData(document.getElementById("modal-danger4")) :
new FormData(document.getElementById("modal-danger8")),
processData: false,
dataType: 'json',
async: false,
contentType: false,
beforeSend: function() {
$(document).find('.alert-danger').text('');
},
success: function(data) {
if (data.status == 0) {
$.each(data.error, function(prefix, val) {
$('.m' + f + ' .' + prefix + '_error').text(val[0]);
});
} else {
}
for (i = 0; i < 30; i++) {
if (x[i].innerHTML) {
y = "true";
}
}
}
});
return y;
}
public function modalValidation(Request $request)
{
$newDate = Carbon::now()->subYears(10);
$validator = Validator::make($request->all(), [
'firstname' => ['required'],
'email' => ['required', 'unique:users', 'digits:9'],
'phone' => ['nullable', 'unique:users', 'email:rfc,dns'],
'email1' => ['required', 'unique:client__ents,email', 'digits:9'],
'phone1' => ['nullable', 'unique:client__ents,phone', 'email:rfc,dns'],
'name' => ['required'],
'job' => ['required'],
'CNI_number' => ['required', 'unique:users', 'digits_between:7,20'],
'CNI_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
'CNI_place' => ['required'],
'raison_sociale' => ['required'],
'forme_juridique' => ['required'],
'siteWeb' => ['nullable', 'url'],
'activité' => ['required'],
'num_contribuable' => ['required', 'unique:client__ents,Numero_contribuable', 'between:13,14'],
'NC_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
'siège' => ['required'],
'email2' => ['required', 'unique:responsable_ents,email', 'digits:9'],
'phone2' => ['nullable', 'unique:responsable_ents,phone', 'email:rfc,dns'],
'CNI_number1' => ['required', 'unique:responsable_ents,CNI_number', 'digits_between:7,20'],
'password' => ['required', 'min:8'],
'confirm_password' => ['same:password'],
'checkbox' => ['accepted'],
],
['confirm_password.same' => 'Ne correspond pas',
'accepted'=>'Veuillez cocher la case avant de continuer',
'required'=>'Ce champ est obligatoire',
'phone.unique'=>'Un utilisateur avec ce mail existe déjà',
'email.unique'=>'Un utilisateur avec ce numéro existe déjà',
'phone1.unique'=>'Un utilisateur avec ce mail existe déjà',
'email1.unique'=>'Un utilisateur avec ce numéro existe déjà',
'phone2.unique'=>'Un responsable avec ce mail existe déjà',
'email2.unique'=>'Un responsable avec ce numéro existe déjà',
'CNI_number.unique'=>'Un utilisateur avec ce numéro de CNI existe déjà',
'CNI_number1.unique'=>'Un responsable avec ce numéro de CNI existe déjà',
'num_contribuable.unique'=>'Un utilisateur avec ce numéro de contribuable existe déjà',
'digits'=>'Veuillez saisir un numéro valide à 9 chiffres',
'digits_between'=>'Numéro CNI(Passeport) non-conforme',
'email'=>'Ce mail est invalide. Doit inclure #',
'date_format'=>'Invalide. Veuillez saisir une date',
'CNI_date.after'=>'Votre CNI ou Passeport ou Récépissé est expiré',
'NC_date.after'=>'Votre Numéro de contribuable est expiré',
'url'=>'Invalide. Veuillez saisir un URL',
'password.min'=>'Minimum 8 caractères',
'num_contribuable.between'=>'Numéro de contribuable non-conforme',
]);
if ($validator->fails())
{
return response()->json(['status'=>0, 'error'=>$validator->errors()->toArray()]);
}
}
<div class="modal-body step-2 m2">
<center>
<h4>Pièce d'identité</h4>
</center>
<div class="form-group">
<label>Numéro CNI(ou Passeport)<i style="color:#FF0000">*</i> :</label>
<input type="number" name="CNI_number" class="form-control" placeholder="Entrer le numéro CNI">
<div class='alert-danger CNI_number_error'></div>
</div>
<div class="form-group">
<label>Date de délivrance<i style="color:#FF0000">*</i> :</label>
<input id="demo-one-input" name="CNI_date" class="form-control" placeholder="Entrer la date">
<div class='alert-danger CNI_date_error'></div>
</div>
<div class="form-group">
<label>Lieu de délivrance<i style="color:#FF0000">*</i> :</label>
<input type="text" name="CNI_place" class="form-control" placeholder="Entrer le lieu">
<div class='alert-danger CNI_place_error'></div>
</div>
<div class="form-group">
<label>Votre photo :</label>
<input type='file' accept="image/*" name="photo" class="form-control" placeholder="image portrait">
</div>
<div class="form-group">
<i style="color:#FF0000">*</i> Champs obligatoires
</div>
</div>

There is no standard validation rule to do this, but you can create a new custom rule.
Check out the documentantion for creating and applying custom rules here:
https://laravel.com/docs/8.x/validation#custom-validation-rules
This link might not scroll down to the right place right away, make sure to look for the topic called: "Custom Validation Rules"

Related

Laravel 9 Vue js 3 multipart form, console showing full html, not only the retrieved data

I'm using a multipart form to send texts and image to database,
The data have been successfully sent to the database, but why in the console it is showing the data infull html ? not only the data that has been retrieved ?
this is my code
<template>
<div class="gabungPage">
<div class="row">
<div class="backgroundGabung" id="hrefGabung">
<div class="tulisanGabung p-5">
<div class="cardGabung">
<p class="teksGabung">Tingkatkan bisnismu sekarang dengan bergabung menjadi mitra JAI'</p>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="nama">Nama</label>
<input
type="text"
id="nama"
v-model="formulirs.nama"
class="form-control"
/>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<input
type="text"
id="alamat"
v-model="formulirs.alamat"
class="form-control"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
v-model="formulirs.email"
class="form-control"
/>
</div>
<div class="form-group">
<label for="nomor">nomor</label>
<input
type="text"
id="nomor"
v-model="formulirs.nomor"
class="form-control"
/>
</div>
<div class="form-group">
<label for="image">Image</label>
<input
type="file"
id="image"
ref="imageInput"
#change="uploadImage"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="tesss">
<h1> <span class="tulisKiri1">Gabung jadi</span> <br> <span class="tulisKiri2">mitra jahit</span></h1>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formulirs: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: null,
},
};
},
methods: {
uploadImage() {
this.formulirs.image = this.$refs.imageInput.files[0];
},
async submitForm() {
const formData = new FormData();
formData.append('nama', this.formulirs.nama);
formData.append('alamat', this.formulirs.alamat);
formData.append('email', this.formulirs.email);
formData.append('nomor', this.formulirs.nomor);
formData.append('image', this.formulirs.image);
axios.post('/api/submit-form', formData).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
},
},
};
</script>
the routes/web.php
Route::post('/api/submit-form', [FormulirsController::class, 'store']);
the controller
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim');
}
I have tried to show the data only by changing to
console.log(response.data)
But it got worse, it only shows full html page in the console, what should I do so that it doesn't display the full html page?
You're making an axios request and returning back method. This is used for redirecting in a monolitic app. I recommend you return a JSON response in your controller. Something like this:
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim'); // this is yours
return response()->json('Data berhasil dikirim'); // 200 status code is the second param by default. You can change for whatever you want.
}

Authentication (Register) in next.js. How to send data to the server?

I am trying to make a user registration function, I have already defined all the states, the endpoint is right but still the front end data does not arrive to the server, I don't know what is going on. In React.js everything was working, I just migrated to Next.js and this function doesn't work anymore.
I am doing it this way :
My code in Next.js :
import React, { useState, useContext } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/router';
// calling the rest api
import axios from '../api/axios';
//icons
import { HiOutlineArrowNarrowLeft } from 'react-icons/hi';
import { AiOutlineArrowLeft, AiOutlineArrowRight } from 'react-icons/ai';
// imgs
import logo from '../assets/logostreaming.png';
import ManLogin from '../assets/man_login.png';
import WomanLogin from '../assets/woman_login.png';
import UserCircle from '../assets/UserCircle.png';
//styles
import styles from '../styles/signup.module.css';
const Signup = () => {
const navigate = useRouter();
// states
const [nif, setNif] = useState('');
const [codPin, setCodPin] = useState('');
const [photoProfile, setPhotoProfile] = useState('');
const [sex, setSex] = useState('');
const [nameUser, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [whatsApp, setWhatsApp] = useState('');
const [password, setPassword] = useState('');
const [dateBirth, setDateBirth] = useState('');
const [codPartners, setCodePartners] = useState(0);
const [confirmationPassword, setConfirmationPassword] = useState('');
const [checked, setChecked] = useState(false);
const [querySelector, setQuerySelector] = useState('close');
const [firstStep, setFirstStep] = useState(true);
const [secondStep, setSecondStep] = useState(false);
const [TreeStep, setTreeStep] = useState(false);
const [error, setError] = useState(false);
const handleFileChange = (e) => {
setPhotoProfile(e.target.files[0]);
}
const handleRegister = (e) => {
e.preventDefault();
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
if (photoProfile == '') {
setError(true);
}
axios.post('/register/',
{
email: email, password: password, phone: phone,
nif: nif, whatsApp: whatsApp, date_birth: dateBirth,
partners_code: codPartners, sex: sex, name: nameUser,
cod_pin: codPin, photo_profile: photoProfile, permission: 1,
c_password: confirmationPassword, obs: 'null'
}, config
)
.then((res) => {
console.log('data res signup register : ', res.data.data);
const id = res.data.data.user.id;
localStorage.setItem('userId', id);
const token = res.data.data.token;
const permission = res.data.data.user.permission;
localStorage.setItem('token', token);
localStorage.setItem('permission', permission);
axios.defaults.headers.Authorization = `Bearer ${token}`;
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
navigate.push('/client/home');
})
.catch((err) => console.log('erro na promise signup register : ', err))
.finally();
}
const QSelector = () => {
setQuerySelector('open')
}
const QSelectorClose = () => {
setQuerySelector('close');
console.log('query selector close : ', querySelector);
}
const nextStep1 = () => {
//e.preventDefault();
if (nameUser == '' || sex == '' || whatsApp == '' || phone == '' || dateBirth == '') {
setError(true);
} else {
setFirstStep(false);
setSecondStep(true);
setTreeStep(false);
}
}
const backToStep1 = () => {
//e.preventDefault();
setFirstStep(true);
setSecondStep(false);
setTreeStep(false)
}
const nextStep2 = () => {
//e.preventDefault();
if (nif == '' || codPin == '' || password == '' || confirmationPassword == '' || email == '') {
setError(true);
} else {
setFirstStep(false);
setSecondStep(false);
setTreeStep(true);
}
}
return (
<div className={styles.container_register}>
<header className={styles.header_register}>
<Image className={styles.Image_logo_register} src={logo} alt="logo pn clique streaming" />
<nav>
<label><HiOutlineArrowNarrowLeft /></label>
<label onClick={() => navigate.push('/')}>Voltar para a página inicial</label>
</nav>
</header>
<div className={styles.container_form}>
<form encType='multipart/form-data' onSubmit={handleRegister} className={styles.form_register}>
{
error
?
<div className={styles.error_form}>
<p>Por favor preencha todos os campos para continuar!</p>
</div>
: ''
}
{
firstStep
?
<div className={styles.container_first_form}>
<Image className={styles.Image_man_register} src={ManLogin} alt="clique man register" />
<div className={styles.container_first_form_div}>
<strong className={styles.title_register}>Dados pessoias</strong>
<p className={styles.slogan}>Registre-se para usufruir dos nossos serviços.</p>
<nav>
<input type="text" name='name' className={styles.input_register} placeholder='Digite o seu nome' value={nameUser} onChange={(e) => [setName(e.target.value), setError('')]} />
<div className={styles.select_wrapper_register}>
<div className={querySelector == 'close' ? styles.select_sex : styles.select_sex_open}>
<div className={styles.select__trigger} onClick={() => querySelector == 'close' ? QSelector() : QSelectorClose()}>
<span>{sex == '' ? 'Qual é o seu sexo ?' : sex}</span>
<div className={styles.arrow}></div>
</div>
<div className={styles.custom_options} onClick={() => QSelectorClose()} >
<span onClick={() => setSex('Homem')}>Homem</span>
<span onClick={() => setSex('Mulher')}>Mulher</span>
</div>
</div>
</div>
<input type="text" name='whatsApp' className={styles.input_register} placeholder='Digite o seu whatsApp' value={whatsApp} onChange={(e) => [setWhatsApp(e.target.value), setError('')]} />
<input type="text" name='phone' className={styles.input_register} placeholder='Digite um número alternativo' value={phone} onChange={(e) => [setPhone(e.target.value), setError('')]} />
<input type="text" name='date_birth' className={styles.input_register_date_birth} placeholder='Data de nascimento (dd/mm/aa)' value={dateBirth} onChange={(e) => [setDateBirth(e.target.value), setError('')]} />
</nav>
<button type='button' className={styles.btn_next_step_register} onClick={nextStep1}>Próximo <AiOutlineArrowRight className={styles.AiOutlineArrowRight} /></button>
</div>
<Image className={styles.Image_woman_register} src={WomanLogin} alt="clique man register" />
</div>
:
secondStep
?
<div className={styles.container_first_form}>
<Image className={styles.Image_man_register} src={ManLogin} alt="clique man register" />
<div className={styles.container_first_form_div}>
<strong className={styles.title_register}>Dados de segurança</strong>
<p className={styles.slogan_2}>Torna a tua conta mais segura.</p>
<nav>
<input type="text" name='nif' className={styles.input_register} placeholder='Digite o seu nif' value={nif} onChange={(e) => [setNif(e.target.value), setError('')]} />
<input type="text" name='cod_pin' className={styles.input_register} placeholder='Digite o seu codigo pin' value={codPin} onChange={(e) => [setCodPin(e.target.value), setError('')]} />
<input type="password" name='password' className={styles.input_register} placeholder='Digite a sua senha' value={password} onChange={(e) => [setPassword(e.target.value), setError('')]} />
<input type="password" name='c_password' className={styles.input_register_c_password} placeholder='Confirma a sua senha' value={confirmationPassword} onChange={(e) => [setConfirmationPassword(e.target.value), setError('')]} />
<input type="email" name='email' className={styles.input_register_date_birth} placeholder='Digite o seu email' value={email} onChange={(e) => [setEmail(e.target.value), setError('')]} />
</nav>
<div className={styles.container_buttons_register}>
<button type='button' className={styles.btn_next_step_register_2} onClick={backToStep1}><AiOutlineArrowLeft className={styles.AiOutlineArrowRight_2} /> Voltar</button>
<button type='button' className={styles.btn_next_step_register_2} onClick={nextStep2}>Próximo <AiOutlineArrowRight className={styles.AiOutlineArrowRight_3} /></button>
</div>
</div>
</div>
:
TreeStep
?
<div className={styles.container_first_form}>
<div className={styles.container_first_form_div}>
<strong className={styles.title_register}>Foto de perfil</strong>
<p className={styles.slogan_2}>Seleciona uma foto de perfil.</p>
<div className={styles.container_first_form_div_2}>
<label htmlFor="photo_profile">
<Image className={styles.Image_user_circle_register} src={UserCircle} alt="clique man register" />
</label>
<input type="file" id='photo_profile' name='photo_profile' className={styles.input_register_file} placeholder='Photo' onChange={(e) => [handleFileChange(e), setError('')]} />
<label>Seleciona uma foto de perfil</label>
<label className={styles.partners}>Deseja se tornar um parceiro ? <input type="checkbox" defaultChecked={checked} onChange={() => setChecked(!checked)} name="partners" /></label>
<button className={styles.button_register} type='submit' onMouseOver={() => sex == '' ? setSex('Homem') : setSex(sex)}>Registrar</button>
</div>
</div>
<Image className={styles.Image_woman_register} src={WomanLogin} alt="clique man register" />
</div>
: ''
}
</form>
</div>
</div>
);
}
export default Signup;
My code in Laravel (server) :
class RegisterController extends BaseController
{
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$input = $request->all();
$n = $validator = Validator::make($input, [
'name' => 'required',
]);
$e = $validator = Validator::make($input, [
'email' => 'required|email',
]);
if ($n->fails()) {
return $this->sendError('Validation name register Error.', $validator->errors());
}
if ($e->fails()) {
return $this->sendError('Validation email register Error.', $validator->errors());
}
$uploadFolder = 'users';
$image = $request->file('photo_profile');
$image_uploaded_path = $image->store($uploadFolder, 'public');
$uploadedImageResponse = Storage::url($image_uploaded_path);
//$input = $request->all();
$input['password'] = bcrypt($input['password']);
$input['photo_profile'] = $uploadedImageResponse;
$user = User::create($input);
$sucess['token'] = $user->createToken('MyApp')->plainTextToken;
$sucess['user'] = $user;
if ($user->permission == 2 || $user->permission == 3) {
AccountStatus::create(['user_id' => $user->id, 'active' => 1]);
AccountBalance::create([
'user_id' => $user->id,
'current_balance' => '0',
'points_accumulated' => 0
]);
CreateSuggestion::create(['user_id' => $user->id, 'account_service_id' => 1]);
}
return $this->sendResponse($sucess, 'User Register with successfully.');
}`

Laravel 5.6 Signed URL not valid after user submit form

In my system, using Laravel 5.6, we send a email with a invitation link (using signed URL) where the user click, fill a form and submit it to the server. In this point the user is saved.
The signed URL already contains data like email and perfil_id (like role_id) that will be assigned when the user submits the form.
At which point should I use the $request->hasValidSignature() method?
Because if I wait for the user to fill the form and submit, the method called here will give false to hasValidSignature(). If I validate when passing the view for the user to see the form, the validation will pass but before sending the form the user will be able to tamper with data.
Signed URL inside controller
$url = URL::temporarySignedRoute('completar', now()->addHours(5), [
'email' => $request->get('email'),
'perfil_id' => $request->get('perfil_id'),
'empresa_id' => auth()->user()->empresa_id,
]);
Mail::to($request->get('email'))->send(new UserRegistrationInvite($url));
Form inside the view that user has to fill after using the link on email
<form action="{{route("aceitar")}}" method="post">
<input type="hidden" name="email" value="{{$request['email']}}">
<input type="hidden" name="perfil_id" value="{{$request['perfil_id']}}">
<input type="hidden" name="empresa_id" value="{{$request['empresa_id']}}">
<input type="hidden" name="signature" value="{{$request['signature']}}">
<br>
<label for="name">Digite seu nome: </label>
<input type="text" id="Nome" name="name" placeholder="Nome">
<br>
<label for="password">Digite sua senha: </label>
<input type="password" name="password" id="password">
<br>
<label for="password_confirmation">confirme sua senha: </label>
<input type="password" name="password_confirmation" id="password_confirmation">
<hr>
<button type="submit" id="convite">Enviar</button>
</form>
function called when user submits form. here validation will fail
public function aceitar(Request $request) {
// verifica se a signed URL é válida
if (!$request->hasValidSignature()) {
abort(response()->json('URL não válida - aceitar', 403));
}
// ao submeter o formulario anterior, faz validação
$validator = Validator::make($request->all(), [
'name' => 'required',
'perfil_id' => 'required',
'empresa_id' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
// se validação falhar exibe erros na tela
if ($validator->fails()) {
return $validator->errors();
} else {
// se passar na validação usuário é criado com perfil e permissões ja relacionadas
$usuario = User::create([
'email' => $request->email,
'name' => $request->name,
'password' => bcrypt($request->password),
'empresa_id' => $request->empresa_id,
]);
$usuario->perfil()->attach($request->perfil_id);
return 'Usuário criado com sucesso';
}
thanks for your time.
The signature is only valid on the first URL that the user visits: 'completar'.
When they post the form, the same signature is no longer valid on the 'aceitar' route.
You can verify the signature before even showing them the form and consider it trusted.
You can also generate another temporary signed URL for the post route in the form if you want to add another validation step.

Laravel 5.2 Flash Old and errors empty after redirect

I have a problem in laravel. This problem it's only in production server, in my local server it's work property. So maybe it's something in the configuration that I don't know.
So when I Send a form, with wrong values the laravel validator system should redirect the user to the form and show the errors.
This is the code my controller:
$rules = array(
'nombre' => 'required|min:3|max:80',
'email' => 'required|email',
'asunto'=>'required|min:3|max:200',
'mensaje'=>'required|min:5|max:1000',
//'g-recaptcha-response' => 'required|recaptcha',
);
$validation = Validator::make($request->all(), $rules);
//si la validación falla redirigimos al formulario de registro con los errores
//y con los campos que nos habia llenado el usuario
if ($validation->fails())
{
return Redirect::to('/#contacto')->withErrors($validation->messages())->withInput();
}
/#contacto is the Home route with the anchor contacto so this should redirect to the home. This is ok.
This is my route.php
Route::get('/', function () {
return view('web.index');
});
Route::post('/contacto/enviar', 'WebController#contacto');
This is my Kernel
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
This is my view that should show the error result.
<form name="contacto" method="post" action="/contacto/enviar"><input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<div class="col-lg-6 col-sm-5 wow fadeInUp delay-05s">
<div class="form"><font color="#ff0000" size="1"><b>{{$errors->first('nombre', ':message')}}</b></font><input class="input-text" type="text" name="nombre" value="<?=Request::old('nombre', 'Nombre y apellido *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('email', ':message')}}</b></font><input class="input-text" type="text" name="email" value="<?=Request::old('email', 'Correo electrónico *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('telefono', ':message')}}</b></font><br><input class="input-text" type="text" name="telefono" value="<?=Request::old('telefono', 'Teléfono (incluya código de área) *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('asunto', ':message')}}</b></font><input class="input-text" type="text" name="asunto" value="<?=Request::old('asunto', 'Asunto');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('mensaje', ':message')}}</b></font><textarea class="input-text text-area" cols="0" rows="0" name="mensaje" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><?=Request::old('mensaje', 'Escriba aquí el mensaje *');?></textarea><font color="#ff0000" size="1"><b>{{$errors->first('g-recaptcha-response', ':message')}}</b></font>{!! Recaptcha::render(['lang'=>'es']) !!}<input class="input-btn" type="submit" value="ENVIAR"></div>
</div></form>
On the top of my view I have a var_dump(Session::all()) and this is the result allways when I submit the form.
array(3) {
["_token"]=>
string(40) "WrQWk9qTH47QrKD6J0Qld8sOhKcUp8xssGpy0F2g"
["_previous"]=>
array(1) {
["url"]=>
string(25) "http://dsnet.dsnet.com.ar"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
In execution of php artisan route:list this is my result, so I have checked that the web middleware is not duplicate.
The estrange thing is that the same code in my local server is working, and in all the form redirect the result are:
array(4) {
["_token"]=>
string(40) "4s1rhoydlH7l84Em792N79ymemNjh4Ep6I8WLNSG"
["errors"]=>
object(Illuminate\Support\ViewErrorBag)#177 (1) {
["bags":protected]=>
array(1) {
["default"]=>
object(Illuminate\Support\MessageBag)#178 (2) {
["messages":protected]=>
array(1) {
["email"]=>
array(1) {
[0]=>
string(40) "The email must be a valid email address."
}
}
["format":protected]=>
string(8) ":message"
}
}
}
["flash"]=>
array(2) {
["new"]=>
array(0) {
}
["old"]=>
array(2) {
[0]=>
string(6) "errors"
[1]=>
string(10) "_old_input"
}
}
["_old_input"]=>
array(7) {
["_token"]=>
string(40) "jzCq4CGGgutPJ3qB2ls1rp7uaiHpcra9Aer1vApC"
["nombre"]=>
string(19) "Nombre y apellido *"
["email"]=>
string(21) "Correo electrónico *"
["telefono"]=>
string(38) "Teléfono (incluya código de área) *"
["asunto"]=>
string(6) "Asunto"
["mensaje"]=>
string(26) "Escriba aquí el mensaje *"
["g-recaptcha-response"]=>
string(0) ""
}
}
I remember that I had the same issue in the local server and I fixed setting the domain configuration on the session config file as null, but this solution doesn't work in the production server. Any Idea?
Finally, I say that the code it's great! There is not problem with the code, but is a problem with the server configuration. I don't know where. But I upload the site to another server and with the setting of the domain = null, of the session configuration work great.

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

Resources