Client Validate array inputs in Yii2 - php

I have many inputs without connect any models in my form like this:
my view is this and I put this to show to other user to detect what is my problem
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Tour */
$this->title = 'ثبت تور';
$this->registerJsFile('#web/storage/js/agency/tour.js', ['depends' => [
\yii\web\JqueryAsset::className(),
\yii\validators\ValidationAsset::className(),
\yii\widgets\ActiveFormAsset::className()],
]);
<?php $form = ActiveForm::begin([
'id' => 'jqTourStep1Form'
]); ?>
<div class="col-xs-6 pull-right padding0">
<?= $form->field($model, 'title_fa')->textInput() ?>
</div>
<div class="form-group col-xs-4 padding0 pull-right idTesttt">
<label class="control-label">Start Date</label>
<input type="text" name="startDate[]" id="startDateTest" class="form-control">
<span class="help-block"></span>
</div>
<?= Html::submitButton('Next', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
tour.js :
/* Validation */
$('#jqTourStep1Form').yiiActiveForm('add', {
id: 'startDateTest',
name: 'startDate',
container: '.idTesttt',
input: '#startDateTest',
error: '.help-block',
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
and I want to Client validate this inputs in Yii 2.
how can I do this ?

You should use each core validator: Each Validator. But you should use ActiveForm to generate form.
public function rules()
{
return [
// checks if every category ID is an integer
['categoryIDs', 'each', 'rule' => ['integer']],
]
}
Add JS code to client side validation:
jQuery('#form-id').yiiActiveForm("add", {
"id": "input-id",
"name": "input-name",
"container": "#container-id or unique .container-class of this input",
"input": "#input-id or unique .input-class",
"validate": function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {"message": "Validation Message Here"});
}
}
);

You can create object of specific validator class without using models:
$validator = new \yii\validators\DateValidator();
and validate any value
$error = null;
$validator->validate($startDate, $error);
method validate() will return boolean and add to variable $error message about error.
You can read and choose specific validator on this page

Related

Uploading image from input field and still getting validation error saying that field is required

Route Code:
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
Route::resource('gallery', GalleryController::class);
});
The Form I'm Using to Upload the File:
<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
#error('gal_img')
<span class="text-danger">{{ $message }}</span>
#enderror
<div class="input-group-append">
<div class="col-sm-10" style="padding-left: 1px;">
<button type="submit" class="btn btn-dark">Save</button>
</div>
</div>
Controller Code:
public function store(GalleryRequests $request)
{
$gal_img = $request->file('gallery_img');
$gal_file = date('YmdHi').$gal_img->getClientOriginalName();
$gal_img->move(public_path('upload/gallery'), $gal_file);
$save_path = 'upload/gallery/'.$gal_file;
Gallery::insert([
'gal_img' => $save_path
]);
$notification = array(
'message' => 'Slider Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Request file validation:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gal_img' => 'required'
];
}
public function messages(){
return [
'gal_img.required' => 'Please Select an Image First',
];
}
The error I get when trying to save after selecting an Image:
Trying to figure out what I've done wrong for hours and am so frustrated right now, please help me to resolve this issue.
Thanks in advance.
Field in form is named gallery_img so that name has to be checked:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gallery_img' => 'required'
];
}
public function messages()
{
return [
'gallery_img.required' => 'Please Select an Image First',
];
}

Laravel 8 - How to suppress validation errors with a back button in Laravel

How to suppress validation errors with a back button in Laravel ??
Details: I have form with two buttons and I made validation how to skip validation when click on (back-button)?
the code in the view page:
<form method="POST" action="{{route("movies.store")}}" class="mt-5 w-50 m-auto">
#csrf
<div class="mb-3">
<label class="form-label">Movie Name</label>
<input type="text" name="movie_name" class="form-control">
#error('movie_name')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Descrption</label>
<input type="text" name="movie_description" class="form-control">
#error('movie_description')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Gener</label>
<input type="text" name="movie_gener" class="form-control">
#error('movie_gener')
<span class="error">{{$message}}</span>
#enderror
</div>
<button type="submit" name="action" value="back" class="btn btn-warning me-3">Back</button>
<button type="submit" name="action" value="add" class="btn btn-primary">Add</button>
</form>
the code in the controller file:
public function store(MoviesFormRequest $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
$data = $request->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
If you just want to solve the problem by implementing back button instead of using button tag use anchor tag as follows
Back
And remove the switch statement and just do as follows:
public function store(MoviesFormRequest $request)
{
Movie::create($request->all());
return redirect()->route("movies.index");
}
Inside your MoviesFormRequest class do all the validations like :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MoviesFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'movie_name' => 'required',
'movie_description' => 'required',
'movie_gener' => 'required',
];
}
}
This will work for you just customize the anchor tag to look good. Hope this solve your problem.
The validation happens in your custom request (MoviesFormRequest) before the code in the controller method is executed.
So in order to skip validation given a specific request input, you have to make the it part of the switch block
use Illuminate\Http\Request;
// use the base request here (no validation at this point)
public function store(Request $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
// in our case block we can validate
$this->validate($request, [
'title' => ['required'],
//... your rules here
]);
$data = $this->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}

CodeIgniter jQuery validator library not work

anyone can help me how to configure CodeIgniter jQuery validator library
Jquery_validation https://github.com/GuriK/CodeIgniter-jQuery-Validator
my Controller
public function create_action()
{
$now = date('Y-m-d H:i:s');
$data = array(
'nama' => $this->input->post('nama',TRUE),
'email' => $this->input->post('email',TRUE),
);
$this->Register_model->insert($data);
}
my View
<span>
<i><img src="<?php echo base_url();?>assets/frontend/images/name.png" alt="" /></i>
<input type="text" class="textbox" name="nama" placeholder="Nama"></span>
Strongly recommend that First of All "Always Read Documents Carefully"
The Author of CodeIgniter jQuery validator library has clearly mentioned all the necessary steps to get this working except one thing that you have to add jQuery validation plugin in your html head :D Well, for experience players that was unnecessary but for beginner for sure it must be mentioned there..
Step - 1: Download zip file from CodeIgniter jQuery validator
& place library/Jquery_validation.php from there to your
CodeIgniter/application/library/Jquery_validation.php
Step - 2: load this library in your Controller
$this->load->library('jquery_validation'); or you can auto load this
library by putting the code $autoload['libraries'] =
array('jquery_validation'); in
CodeIgniter/application/config/autoload.php.
Step - 3: Create some required code to get this work.
// set validation rule to jquery validation lib
$this->jquery_validation->set_rules($rules);
// set validation message to jquery validation lib
$this->jquery_validation->set_messages($messages);
// create jquery validation script for form #login-form
$validation_script = $this->jquery_validation->run('#login-form');
Step - 4: Don't forget to add jQuery validation plugin in
your view
& finally here is full working example code:
<?php
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
* Class Controller
*
* Class Logins Controller to handle login & logout
*/
class Logins extends CI_controller
{
/**
* Class Constructor
*/
public function __construct()
{
// execute parent class constructor
parent::__construct();
// load helpers
$this->load->helper(array('form', 'url', 'security'));
// load codeigniter for validation lib
$this->load->library('form_validation');
// load jquery validation lib
$this->load->library('jquery_validation');
}
/**
* Default method to execute if method name missing
* #return [type] [description]
*/
public function index()
{
// check if user login or not
if (!$this->session->userdata('name')) {
// form validation rules
$rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
),
array(
'field' => 'pass',
'label' => 'Secret Password',
'rules' => 'required',
),
);
// form validation message
$messages = array(
'name' => array(
'required' => "jQuery validation User Name is required",
'min_length' => "jQuery validation, Please enter more then 3 char",
'max_length' => "jQuery validation, Please enter less then 25 char",
),
'pass' => array('required' => "jQuery validation Password is required"),
);
// set validation rule to jquery validation lib
$this->jquery_validation->set_rules($rules);
// set validation message to jquery validation lib
$this->jquery_validation->set_messages($messages);
// create jquery validation script for form #login-form
$validation_script = $this->jquery_validation->run('#login-form');
// collect script and send to view
$data = ['validation_script' => $validation_script];
// show login view
$this->load->view('form', $data);
}
// if already logged in, show other view
else {
// get name from session login flag
$name = $this->session->userdata('name');
// load view
$this->load->view('form', $name);
}
}
/**
* login Form POST Method to verify Users identity
* #return [type] [description]
*/
public function do_login()
{
// if POST made then only
if ($this->input->post()) {
// form validation rule for codeigniter validation
$rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
),
array(
'field' => 'pass',
'label' => 'Secret Password',
'rules' => 'required',
),
);
// custom validation message for server side form validation
$this->form_validation->set_message('required', 'CodeIgniter validation, The %s is required filed');
$this->form_validation->set_message('min_length', 'CodeIgniter validation, The %s Please enter more then 3 char');
$this->form_validation->set_message('max_length', 'CodeIgniter validation, The %s Please enter less then 25 char');
// form validation using codeigniter built-in lib
$this->form_validation->set_rules($rules);
// check validation
if ($this->form_validation->run() === false) {
// validation failed
$this->load->view('form');
} else {
// safe from CSRF, use 2nd param as TRUE in POST
$name = $this->input->post('name', true);
$pass = $this->input->post('pass', true);
// if result
if ($name == 'admin' && $pass == 'admin') {
$sess_login = array(
'name' => $name,
);
// set session login flag
$this->session->set_userdata($sess_login);
// load view
$this->load->view('form', $name);
} else {
redirect('logins');
}
}
} else {
redirect('logins');
}
}
/**
* Log Out Method
* #return [type] [description]
*/
public function userlogout()
{
$this->session->unset_userdata('name');
redirect('logins');
}
}
/* End of file logins.php */
/* Location: ./application/controllers/logins.php */
& here is view source code:
<?php
$name = $this->session->userdata('name');
?>
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter jQuery validation</title>
<!-- load bootstrap css -->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- load jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- load bootstrap js -->
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- load jquery validation javascript plugin -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<!-- echo jQuery form validation script from Controller -->
<script type="text/javascript">
<?php echo $validation_script;?>
</script>
</head>
<body>
<div class="jumbotron vertical-center">
<?php if ($name !== false): ?>
<div class="container">
<div class="alert alert-success">Wohoo!! You made it.. <?php echo $name ?> Log Out</div>
</div>
<?php else: ?>
<div class="container">
<?php echo (validation_errors()) ? '<div class="alert alert-danger">'.validation_errors().'</div>' : ''; ?>
<?=form_open('logins/do_login', 'id="login-form" class="form-controller"'); ?>
<fieldset>
<legend>Login Information</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Please enter your user name here" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="password">Secret Password</label>
<input type="password" class="form-control" id="password" name="pass" placeholder="Please enter your password here" value="<?php echo set_value('pass'); ?>">
</div>
</fieldset>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button type="submit" class="btn btn-primary">Sign in</button>
</div>
</div>
<?=form_close();?>
</form>
</div>
<?php endif ?>
</div>
</body>
</html>
You can see the demo by using http://localhost/CodeIgniter/logins url in your browser.

Posting content into the database with an image using Laravel

I'm trying to post some stuff into the database using laravel, but It seems not to work...
This is what I get:
The HTML:
{{ Form::open(array('role' => 'form')) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile1">Nieuws afbeelding</label>
<input type="file" name="img">
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
That displays all well....
Exept when I try to 'post' the news, because that is what I try to do, it just refreses the page. The URL to that page is mydomain.com/admin/news/write
My router looks like this:
Route::resource('admin/news/write', 'AdminController#create');
First it was authenticated in a group:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
Route::resource('admin/news/write', 'AdminController#create');
});
This all works, but when I change the Route::resource('admin/news/write', 'AdminController#create'); to Route::post('admin/news/write', 'AdminController#create'); I get an error, that I can't see...
Good, now my controller:
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
if (Input::only('title', 'message'))
{
return Redirect::to('admin/news/write')->with('message', 'Het nieuws werd gemaakt!');
}
}
else
{
return Redirect::to('admin/news/write')->with('message', "Er ging iets mis: ")->withErrors($validator);
}
}
The problem is, I don't know how I can store an image to
/public/pictures/news
And then store the full file name into the database, if someone could help me out... I need a response quick, beacause I have a deadline... :{
Kindest regards
First you need to tell your form using the laravel helper that this is going to be uploading a file...
Form::open(['method'=>'POST', 'role' => 'form', 'files' => true])
In your controller you want to get the file from the input
$imgFile = Input::file('img');
Now to move the file from the temporary location it's been uploaded, to a more permanent location call the following (where $filename is what you want to call the uploaded file)...
$dir = '../storage/app/upload/';
$imgFile->move($dir.$filename);
The path for the root of the app from here is ../ (one up from public) so..
../storage/app/upload/ would be a great location to use for uploaded files.
You can then just write:
$dir.$filename;
back to the database - job done :)
Edit :: -- Your Controller --
Your controller for parsing this is based on resources...
So your route will be:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
}
Your controller itself will have a structure such as (remembering this: http://laravel.com/docs/4.2/controllers#restful-resource-controllers):
class AdminController extends BaseController {
public function index(){...}
public function create(){...}
public function
//The store() method is an action handled by the resource controller
//Here we're using it to handle the post action from the current URL
public function store()
{
$imgFile = Input::file('img');
//processing code here....
}
public function show(){...}
public function edit(){...}
public function update(){...}
public function destroy(){...}
}
I fixed the issue.
My controller:
<?php
class AdminNewsController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('admin.news.create');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admin.news.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
'publish' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/news/create')->withErrors($validator);
}else{
//store
$news = new News;
$news->title = Input::get('title');
$news->message = Input::get('message');
$news->img_url = Input::file('img')->getClientOriginalName();
$news->posted_by = Auth::user()->username;
$news->published_at = time();
$news->published = Input::get('publish');
$news->save();
//save the image
$destinationPath = 'public/pictures/news';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/pictures/news', $file->getClientOriginalName());
}
//redirect
Session::flash('success', 'Nieuws succesvol aangemaakt!');
return Redirect::to('admin/news/create');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My create.blade.php
<div class="portlet-body form">
{{ Form::open(['method'=>'POST', 'role' => 'form', 'files' => true]) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label>Nieuws afbeelding</label>
{{ Form::file('img') }}
</div>
<div class="form-group">
<label>Bericht publiceren?</label>
<div class="radio-list">
<label class="radio-inline">
<span>
{{ Form::radio('publish', '1') }}
</span>
<b style="color:green">Publiceren</b>
</label>
<label class="radio-inline">
<span>
{{ Form::radio('publish', '0', true) }}
</span>
<b style="color:red">Niet publiceren</b>
</label>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
</div>
Then It all work!
Thanks to Matt Barber for the help!

display form error messages underneath the input fields Phalcon php

Is there a way to display error messages underneath the input fields of a form if a field didn't pass validation? Can I somehow process form in the same action (User/index in my case) that the form is displayed and then send those error messages to view? What I have is : index.volt:
<div class="loginForm">
<form action=<?= $form->getAction(); ?> method="POST">
<label for="username">Username: </label>
<?= $form->render('username'); ?>
<br/>
<label for="password">Password: </label>
<?= $form->render('password'); ?>
<br>
<?= $form->render('login'); ?>
</form>
</div>
LoginForm.php:
<?php
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Text,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Submit,
Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\StringLength;
class LoginForm extends Form {
public function initialize()
{
$this->setAction('login');
$username = new Text('username');
$username->addValidator(new PresenceOf(array (
'message' => 'Can\'t be empty'
)));
$password = new Password('password');
$password->addValidator(new PresenceOf(array (
'message' => 'Can\'t be empty'
)));
$submit = new Submit('login', array('value' => 'Login'));
$this->add($username);
$this->add($password);
$this->add($submit);
}
}
And UserController.php:
<?php
class UserController extends \Phalcon\Mvc\Controller
{
/**
* login form
* #var LoginForm
*/
private $_loginForm;
public function initialize()
{
$this->_loginForm = new LoginForm();
}
public function indexAction()
{
$this->view->setVar('form', $this->_loginForm);
}
public function loginAction()
{
if($this->request->isPost()) {
if (!$this->_loginForm->isValid($this->request->getPost())) {
foreach ($this->_loginForm->getMessages() as $message) {
echo $message. '<br />';
// redirect to User/index and pass error messages to view to display them to a user
}
}
}
}
}
EDIT:
Or it would be even better to process this form on the same action that it is displayed. How can I do this?
First, what you have provided in your index.volt isn't volt content. See here how to configure Volt and use the Volt language in your views.
What you're asking for is called flashing messages in Phalcon.
Unfortunately, in the current version you can just flash messages based on type(success, error, warning, etc.) but you can create your own type, so let's fake that the type means the input name.
UserController.php
...
public function loginAction()
{
if($this->request->isPost()) {
if (!$this->_loginForm->isValid($this->request->getPost())) {
$messages = $this->_loginForm->getMessages();
$userMessage = $messages->filter('username');
if(count($userMessage))
$this->flash->message('username', $userMessage[0]);
$passMessage = $messages->filter('password');
if(count($passMessage))
$this->flash->message('username', $passMessage[0]);
return $this->dispatcher->forward(["action" => "index"]);
} else {
//Login
}
}
index.volt
<div class="loginForm">
<form action="{{form.getAction()}}" method="POST">
<label for="username">Username: </label>
{{form.render('username')}}<br/>
{{ flash.has('username') ? flash.output('username') : '' }}
<label for="password">Password: </label>
{{form.render('password')}}<br>
{{ flash.has('password') ? flash.output('password') : '' }}
{{form.render('login')}}
</form>
</div>

Categories