proengsoft / laravel-jsvalidation Goto Github PK
View Code? Open in Web Editor NEWLaravel Javascript Validation
License: MIT License
Laravel Javascript Validation
License: MIT License
Hi! I want to know how to implements my own validation methods that extends from laravel validation class? or How to use these methods?
I follow the FormRequest Example, validation work fine, but when I press the submit button, nothing happens
please some help
{!! JsValidator::formRequest('App\Http\Request\StoreBlogPostRequest', '#my-form'); !!}
Should be
{!! JsValidator::formRequest('App\Http\Requests\StoreBlogPostRequest', '#my-form'); !!}
And the name of the template post_edit.balde.php should be post_edit.blade.php.
Very minor stuff. But the typo in the form request example had me chasing a non-existent error for a couple of hours.
Excellent piece of work though. Cheers.
Hi,
I include your plugin so:
<script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>{!! $validator !!}
Generated Code:
<script> jQuery(document).ready(function(){ $("form").validate({ highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group, .checkbox').addClass('has-error'); // set error class to the control group }, unhighlight: function (element) { // revert the change done by hightlight $(element) .closest('.form-group, .checkbox').removeClass('has-error'); // set error class to the control group }, errorElement: 'p', //default input error message container errorClass: 'help-block help-block-error', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", // validate all fields including form hidden input errorPlacement: function(error, element) { alert("ERROR"); if (element.attr("type") == "radio") { error.insertAfter(element.parents('div').find('.radio-list')); } else if (element.attr("type") == "checkbox") { error.insertAfter(element.parents('label')); } else { if(element.parent('.input-group').length) { error.insertAfter(element.parent()); } else { error.insertAfter(element); } } }, success: function (label) { label.closest('.form-group, .checkbox').removeClass('has-error'); // set success class to the control group }, rules: {"username":{"laravelRequired":[]},"password":{"laravelRequired":[]}} , messages: {"username":{"laravelRequired":"The username field is required."},"password":{"laravelRequired":"The password field is required."}} }) }) </script>After that I Build in a debug message, If your plugin detect an error.
errorPlacement: function(error, element) {
alert("ERROR");
When I submit my form I get these alert, but after I click ok, the was sent.
Whats the error ?
composer update executed the last hour.
messages
array will be always empty.
vendor/proengsoft/laravel-jsvalidation/src/Validator.php
public function validationData()
{
$jsMessages = array();
$jsValidations = $this->generateJavascriptValidations();
return [
'rules' => $jsValidations,
'messages' => $jsMessages,
];
}
Am I missed something? Because in previous version as I understand messages array were taken from generateJavascriptValidations()
method:
public function js()
{
list($jsRules, $jsMessages)=$this->generateJavascriptValidations();
return [
'rules' => $jsRules,
'messages' => $jsMessages
];
}
Displaying messages still working. This array key is deprecated or what?
Hello, really good work with this package, it is simple and effective.
I am only having problems with the "required_without" and "required_without_all" rules in my application.
I have a field 'email' which should be required if none of fields 'phone1', 'phone2' and 'phone3' are present (required_without_all), and field 'phone1' should be required if 'email' is not present (required_without).
When all fields are empty it works as expected, validation fails giving a message that field is required when the other is not present. The problem is when I fill in any of the fields, validation still fails (e.g. phone1 is present and email is empty, but validation fails saying "phone1 is required when email is not present"), even if all fields are filled correctly the validator will keep failing saying a field is required when the other is empty when both fields are filled.
I have tested my code without jsvalidation and the Laravel validation works as expected, only when I add JS validation I get this error.
The generated HTML for the page is here: http://pastebin.com/rapW1yva
I am still a newbie in this, so I hope this is a valid issue, if it is not, excuse me.
Regards,
Lorenzo
Hello!
How can I use unique parameter for check email or username in DB?
Thanks
The confirmed field for password shows that the passwords (password and password_confirmation) do not match. The rules are set as follows:
public function rules() { return [ 'username' => 'required|min:5|max:50|unique:users', 'email' => 'required|email|unique:users', 'password' => 'required|min:8|confirmed', 'password_confirmation' => ' 'required|min:8', 'g-recaptcha-response' => 'required|recaptcha', ]; }
My Laravel Version is 5.1
A nice feature will be to allow disable javascript validations for certain attributes.
JS is rendered with these rules but validation doesn't work (actual value isn't applied)
Laravel's Auth controller (see link below) doesn't have an obvious way to add jsvalidation and pass it to the /auth/login view. Can this specialized case be documented somewhere?
The following validation fails on the number 9
'postcode' => 'required|max:7|string',
It seems to ignore the string rule and act as if the number may not be greater then 7 while w're trying to check for a string length.
Hi Albert,
I trying to do this validation on a FormRequest on a update method of a controller.
'contacto.email' => 'email|unique:users,email,id,'.$this->segment(2),
The url is something like
http://proyect.dev/clientes/401/edit
I try too
'contacto.email' => 'email|unique:users,email,id,'.$this->get('id'),
Because the method is
public function update(ClientesRequest $request, $id)
I get an error
QueryException in Connection.php line 636:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '401' in 'where clause' (SQL: select count(*) as aggregate from gs_users
where email
= [email protected] and 401
<> id)
As you see, the query is extrange. I thik is a problem of Laravel.
What do you think?
Best regards
Hello,
I'm trying to use this with Laravel 5.1, but there seems to be an issue with the required version of laravel
Any help!?
$ composer require proengsoft/laravel-jsvalidation:~1.0
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Conclusion: remove laravel/framework v5.1.1
- Conclusion: don't install laravel/framework v5.1.1
- proengsoft/laravel-jsvalidation v1.0.0 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- proengsoft/laravel-jsvalidation v1.0.0-rc1 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- proengsoft/laravel-jsvalidation v1.0.1 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- proengsoft/laravel-jsvalidation v1.0.2 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- proengsoft/laravel-jsvalidation v1.0.3 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- proengsoft/laravel-jsvalidation v1.0.4 requires illuminate/contracts 5.0.* -> satisfiable by illuminate/contracts[5.0.x-dev, v5.0.0, v5.0.33].
- don't install illuminate/contracts 5.0.x-dev|don't install laravel/framework v5.1.1
- don't install illuminate/contracts v5.0.0|don't install laravel/framework v5.1.1
- don't install illuminate/contracts v5.0.33|don't install laravel/framework v5.1.1
- Installation request for laravel/framework == 5.1.1.0 -> satisfiable by laravel/framework[v5.1.1].
- Installation request for proengsoft/laravel-jsvalidation ~1.0 -> satisfiable by proengsoft/laravel-jsvalidation[v1.0.0, v1.0.0-rc1, v1.0.1, v1.0.2, v1.0.3, v1.0.4].
Installation failed, reverting ./composer.json to its original content.
My FormRequest
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required|confirmed',
];
}
Converted to:
rules: {
"email": {
"laravelValidation": [
[
"Required",
[
],
"The email field is required.",
true
],
[
"Email",
[
],
"The email must be a valid email address.",
false
]
]
},
"password_confirmation": {
"laravelValidation": [
[
"Required",
[
],
"The password field is required.",
true
],
[
"Confirmed",
[
"password"
],
"The password confirmation does not match.",
false
]
]
}
},
messages: [
],
There are no password field rules, they were applied to password_confirmed somehow.
Enhancement proposal.
When user trying to submit form with required
input[type='text']
or input[type='radio']
- there are error raising.
In case when user starting to type inside input[type='text']
- field re-validating and an error disappearing, but when input[type='radio']
state changing re-validation not firing. Is there is a way to re-validate radio buttons on selector change and hide error block in case of success?
I'm using JsValidator::formRequest to validate my forms using custom request classes.
My rules:
return [
'code' => 'required|unique|min:4|max:16',
'type' => 'required',
'amount' => 'required'
];
Validation seems to be working, I get errors when I should, and no errors when I shouldn't, but the form never submits.
Hello,
input custom attributes that are changed in overriden attributes()
method in custom Request file are not applied in JS validation rules (despite the fact that backend returns proper names)
is it possible to show errors in tooltips ?
File size is being treated as string size
When validates laravel
"The logo may not be greater than 100 kilobytes."
When validates javascript
"The logo may not be greater than 100 characters."
I do the configuration based on the example on this web.
When I submit the form I got this error on the JS console:
💥 TypeError: a.validator.methods[d] is undefined 💥
Version of jquery validation: 1.13.1
Version of Laravel-jsvalidation: latest
The form request rules:
public function rules()
{
return [
"test1" => "required|integer|min:0",
"test2" => "required|url|min:5|max:100",
"test3" => "required|min:5|max:100",
"test4" => "required|min:5|max:100"
];
}
The view:
<div class="container">
{!! Form::open(['route' => 'test.store', 'method' => 'post', 'id' => 'testForm', 'class' => 'form-horizontal']) !!}
{!! Form::hidden('test1', 0, ['id'=>'test1']) !!}
<div class="form-group">
{!! Form::label('test2', 'Test2') !!}
{!! Form::text('test2', null, ['id'=>'test2', "class" => "form-control typeahead", 'placeholder'=>'Type your test2']) !!}
</div>
<div class="form-group">
{!! Form::label('test3', 'Test3') !!}
{!! Form::text('test3', null, ['id'=>'test3', "class" => "form-control", 'placeholder'=>'Type your test3']) !!}
</div>
<div class="form-group">
{!! Form::label('test4', 'Test4') !!}
{!! Form::text('test4', null, ['id'=>'test4', "class" => "form-control", 'placeholder'=>'Type your test4']) !!}
</div>
<div class="form-group">
{!! Form::submit('OK', ["class" => "btn btn-success btn-block"]) !!}
</div>
{!! Form::close() !!}
</div>
{!! JsValidator::formRequest('App\Http\Requests\TestForm', '#testForm'); !!}
The js generated:
jQuery(document).ready(function(){
$("#testForm").validate({
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group, .checkbox').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.form-group, .checkbox').removeClass('has-error'); // set error class to the control group
},
errorElement: 'p', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
errorPlacement: function(error, element) {
if (element.attr("type") == "radio") {
error.insertAfter(element.parents('div').find('.radio-list'));
}
else if (element.attr("type") == "checkbox") {
error.insertAfter(element.parents('label'));
}
else {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
},
success: function (label) {
label
.closest('.form-group, .checkbox').removeClass('has-error'); // set success class to the control group
},
rules: {"test1":{"laravelRequired":[],"laravelInteger":[],"laravelMin":["0"]},"test2":{"laravelRequired":[],"laravelUrl":[],"laravelMin":["5"],"laravelMax":["100"]},"test3":{"laravelRequired":[],"laravelMin":["5"],"laravelMax":["100"]},"test4":{"laravelRequired":[],"laravelMin":["5"],"laravelMax":["100"]}} ,
messages: {"test1":{"laravelRequired":"The test1 field is required.","laravelInteger":"The test1 must be an integer.","laravelMin":"The test1 must be at least 0."},"test2":{"laravelRequired":"The test2 field is required.","laravelUrl":"The test2 format is invalid.","laravelMin":"The test2 must be at least 5 characters.","laravelMax":"The test2 may not be greater than 100 characters."},"test3":{"laravelRequired":"The test3 field is required.","laravelMin":"The test3 must be at least 5 characters.","laravelMax":"The test3 may not be greater than 100 characters."},"test4":{"laravelRequired":"The test4 field is required.","laravelMin":"The test4 must be at least 5 characters.","laravelMax":"The test4 may not be greater than 100 characters."}} })
})
Do you have any idea to fix this?
Thanks.
I've got an error in Firefox console:
TypeError: $.validator.methods[method] is undefined
In Chrome:
jquery.validate.js:617 Uncaught TypeError: Cannot read property 'call' of undefined
Unique Roles currently are not checked via your plugin.
How can I use it ?
Currently I use version 1.1.1 ... thanks!
Hello I try to implement laravel-jsvalidation in my app, and in controller I try:
$validator = JsValidator::make(['field0' => 'min:3']);
return view('registration.registration')->with(['validator' => $validator]);
and than in view:
{!! $validator !!}
and I get:
Manager::__toString() must not throw an exception error
What's the problem? It's laravel 5.1
JSon Rule, introduced on August is not supported
Hi Albert,
I think there is a problem with the password, password confirmation validation on the javascript side.
This are the rules:
'contacto.password' => 'min:3|confirmed',
'contacto.password_confirmation' => 'min:3'
When I submit the form, in server side, the validation it's verified correctly. But previously, in client side the "confirmed" validation is not executed, only the "min:3".
I don't see any reference to the confirmed rule in the html/javascript generated code.
Is this rule implemented yet?
Best regards
I do not know how to resolve this, so I am opening a github ticket.
I am unable to use the JsValidator, as I get this error - 'Call to undefined method Proengsoft\JsValidation\JsValidator::make()'
Code snippets
//Imported the correct class
use Proengsoft\JsValidation\JsValidator;
//Called the correct method
$rules = [
'owner_name' => 'required',
'owner_pan' => 'required',
'owner_email' => 'required|email',
'owner_mobile' => 'required',
'owner_std_code' => 'required',
'owner_landline' => 'required',
];
$validator = JsValidator::make($rules);
//Still the below exception gets thrown on Runtime.
Call to undefined method Proengsoft\JsValidation\JsValidator::make()
Hello:
I fork your repository to add a new feature in your component:
When We are validating the form I want to move the view to the first error and set the focus on the first component on my form.
I added two new parameters on the config to active or not this feature and to control the time of the animate to move the scroll.
PD: I created a pull requet at #32
Thank you
Samuel
As the rules and messages are the key thing to grab from one's Laravel app, I think it'd be useful to have access to this stuff as a JSON object.
I did this on my view
with the code below, but it'd be nice to have an option to generate the Javascript code that I did. Basically, I got rid of the Bootstrap styling. To be clear, I am using Bootstrap but it doesn't seem necessary for the JSValidator instance to generate all that styling code on every view when you could just set defaults on your template page. Here's the boilerplate default modification to make Bootstrap styling work.
<?php $validator = JsValidator::formRequest('App\Http\Requests\EngagementsRequest', '.requiresValidation');?>
<?php $json_rules = json_encode($validator->rules);?>
<script>
$(function(){
$('.requiresValidation').validate({
rules: <?php echo $json_rules;?>
});
});
</script>
Hi,
following situation:
use Proengsoft\JsValidation\JsValidator;
protected $validationRules=[
'email' => 'required|email',
'password' => 'required',
];
$validator = JsValidator::make($this->validationRules);
return view('base::login.login')->with('validator', $validator);
Gives the error in issue subject.
Where is the error ?
Improve code decoupling in JsValdidator
class for better testeability
Here are my rules:
public function rules()
{
return [
'date_start' => 'date|date_format:d-m-Y|before:date_finish',
'date_finish' => 'date|date_format:d-m-Y|after:date_start',
];
}
Outcomes from varying input:
Input
date_start: 10-10-2015
date_finish: 10-10-2016
Messages
date_start: "The date start must be a date before date finish."
date_finish: Nothing
Input
date_start: 10-10-2017
date_finish: 10-10-2016
Messages
date_start: "The date start must be a date before date finish."
date_finish: Nothing
Input
date_start: 10-10-2016
date_finish: 10-10-2016
Messages
date_start: "The date start must be a date before date finish."
date_finish: Nothing
Please note I've tried with my rules like this
public function rules()
{
return [
'date_start' => 'before:date_finish',
'date_finish' => 'after:date_start',
];
}
and this
public function rules()
{
return [
'date_start' => 'date|date_format:Y-m-d|before:date_finish',
'date_finish' => 'date|date_format:Y-m-d|after:date_start',
];
}
Any guidance if I'm doing something wrong would be most appreciated! Excellent package btw, big thanks to the creator.
Hello,
I have this in my formrequest :
$id = Sentinel::getUser()->id;
return $rules = [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users,email,' . $id
];
the probleme is the last line...because all work without it...
I cant'submit the form...submit button don't work...
Hello,
I'm trying to validate login form following your FormRequest Validation example in my view
{!! JsValidator::formRequest('App\Http\Request\UserLoginRequest'); !!}
and my UserLoginRequest
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserLoginRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required|min:5'
];
}
}
Still I'm getting error
App\Http\Request\UserLoginRequest must extends 'Illuminate\Foundation\Http\FormRequest' ..
Could you pls give me some hint what I'm missing?
Thanks
If hidden input presented - validator trying to validate it instead of visible fields.
<label>Rate user</label>
<input type="hidden" name="rating" value="">
<div class="radio-list">
<span class="star-rating">
<input id="rating5" type="radio" name="rating" value="5">
<label for="rating5">5</label>
<input id="rating4" type="radio" name="rating" value="4">
<label for="rating4">4</label>
<input id="rating3" type="radio" name="rating" value="3">
<label for="rating3">3</label>
<input id="rating2" type="radio" name="rating" value="2">
<label for="rating2">2</label>
<input id="rating1" type="radio" name="rating" value="1">
<label for="rating1">1</label>
</span>
</div>
In current example rating
field is required
. Even if one of the visible radio controls is checked - validator ignores it and continue to display an error that rating is required (it rendering right after hidden input). But as soon as value of hidden input will be setted as value="0"
- form will work as expected.
As I know in HTML each next checked control overriding values of controls with same named which were met before and only latest one is sending. In current case it looks like validator trying to validate first occurrence.
The rules that depends from other rules only are validated when the dependant filed has any rule.
In this case JsValidation works as expected
$rules = array(
'password'=>'required_with:username',
'username'=>'min:3',
);
But in this other case JsValidation throws an Javascript Exception and form is submitted.
$rules = array(
'password'=>'required_with:username',
'username'=>'min:3',
);
Hey,
How can I create multiple instance of jsvalidation and use it in a view? (for multiple forms with different rules).
Thanks
When the format specified in DateFormat rule result in a invalid date. JsValidation don't pass the validation
$rules = array(
'month' => 'date_format:m'
);
The config key form_selector
is not loaded when package boots
Excellent package, should be part of the Laravel core in my opinion, but there you go. However, I can't seem to get this to work using Route Model binding for edit form. I am using the Eloquent-Sluggable package in order to reference via slug rather than id:
https://github.com/cviebrock/eloquent-sluggable
Here is an example using Menu as an example:
app/Http/RouteServiceProvider.php
public function boot(Router $router)
{
$router->bind('menus', function($slug)
{
return Menu::findOrThrowException($slug);
});
}
app/Http/Providers/UpdateMenuRequest.php
public function rules()
{
return [
'title' => 'required|unique:menus,title,' . $this->route('menus')->id,
];
}
menus/edit.php
{!! JsValidator::formRequest('App\Http\Requests\UpdateMenuRequest', '#menu') !!}
I get the following error:
ErrorException in UpdateMenuRequest.php line 27:
Trying to get property of non-object (View: /home/vagrant/Code/TpsCMS/resources/views/admin/menus/edit.blade.php)
Line 27 being...
'title' => 'required|unique:menus,title,' . $this->route('menus')->id,
Could you pleas advise me further?
Is it possible to add custom js methods? I tried this and added this to my rules but it doesn't get added to the rules on the page.
If there are more than 1 radio-list in form - when one of the radio controls raising an error - all radio-lists are displaying it. Even if they don't have validation rules.
For example, Gender is required and Habbits don't have any rules specified.
<div>
<label>Gender</label>
<div class="radio-list">
<input type="radio" name="gender" value="1" /> Female
<input type="radio" name="gender" value="2" /> Male
</div>
</div>
<div>
<label>Habbits</label>
<div class="radio-list">
<input type="radio" name="habbits" value="0" /> No
<input type="radio" name="habbits" value="1" /> Smoking
</div>
</div>
Result will be:
<div>
<label>Gender</label>
<div class="radio-list">
<input type="radio" name="gender" value="1" /> Female
<input type="radio" name="gender" value="2" /> Male
</div>
<p class="help-block help-block-error" id="gender-error">The gender field is required.</p>
</div>
<div>
<label>Habbits</label>
<div class="radio-list">
<input type="radio" name="habbits" value="0" /> No
<input type="radio" name="habbits" value="1" /> Smoking
</div>
<p class="help-block help-block-error" id="gender-error">The gender field is required.</p>
</div>
The js is not using laravel´s language file when I call the numeric/number validation. It works as validation but it is using the Javascript language string.
$validationRules=[
'title' => 'required|max:100',
'description' => 'required|max:1000',
'plan' => 'required',
'winners' => 'required|numeric|min:1',
'tags' => 'required|numeric',
'category' => 'required',
'draw_at' => 'required|date_format:d/m/Y H:i|after:now'
];
Hello,
First of all, You have done a great job.
Right now i am validating a filed with name/id "desc", but i don't want to the message like this "The desc field is required." .
So, How can i change the default validation message ? either to be "The description field is required." or at least "This field is required." ?
Note: The validation.required expecting passing a variable :attribute so when i try to remove this variable the code crashes.
Regards,
Amir
public function rules()
{
return [
'name' => 'required|min:2|max:1000',
'base_occupancy' => 'required|integer|min:0|max:100',
'max_occupancy' => 'required|integer|min:0|max:100'
];
}
even if i give values between 0&100, its showing error
When attribute has multiple times the same rule, only the last one is validated
In this case, for the attribute distributor_city_id
the rule required_if:type,distributor
is not validated
$rules=[
'distributor_city_id' => 'required_if:type,distributor|required_if:house,myhome',
'distributor_name_id' => 'required_if:type,distributor',
'type' => 'alpha',
'house' => 'alpha',
];
Add Tests for the package
It works with 'jpg', 'png', 'gif', 'bmp', 'svg' but not with 'JPG', 'PNG', 'GIF', 'BMP', 'SVG'.
Thank's
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.