boekkooi / jqueryvalidationbundle Goto Github PK
View Code? Open in Web Editor NEWJquery validation form bundle for symfony 2
License: MIT License
Jquery validation form bundle for symfony 2
License: MIT License
Hi Boekkoi,
Do you know what can cause this error ?
Method "groups" for object "Boekkooi\Bundle\JqueryValidationBundle\Form\Rule\TransformerRule" does not exist in BoekkooiJqueryValidationBundle:Form:macros.js.twig at line 49
I think it has appeared after a composer update on dev-master.
I've tried with the 1.0.3 version, there is no problem.
Thank you
I don't understand how I can use the bundle with validation groups. I only get this exception: Callable validation_groups are not supported. Disable jquery_validation or set jquery_validation_groups
.
Googling jquery_validation_groups
only returns the doc that say to set jquery_validation_groups... but where/how?
The option validation_groups is a callback so - according to documentation - I have to define the option jquery_validation_groups as array (or string).
# AppBundle/Form/UserType.php
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
'jquery_validation_groups' => array(
self::VALIDATION_GROUP_REGISTRATION_AUSTRIA,
self::VALIDATION_GROUP_REGISTRATION_SWITZERLAND,
self::VALIDATION_GROUP_REGISTRATION_ITALY,
self::VALIDATION_GROUP_REGISTRATION_GERMANY,
self::VALIDATION_GROUP_REGISTRATION,
),
'validation_groups' => function (FormInterface $form) {
if ($form->getData() !== null && null !== $form->getData()->getCountry()) {
$country = $form->getData()->getCountry();
switch ($country) {
case '2':
return array(self::VALIDATION_GROUP_REGISTRATION_AUSTRIA);
break;
case '3':
return array(self::VALIDATION_GROUP_REGISTRATION_SWITZERLAND);
break;
case '4':
return array(self::VALIDATION_GROUP_REGISTRATION_ITALY);
break;
default:
return array(self::VALIDATION_GROUP_REGISTRATION_GERMANY);
break;
}
} else {
return array(self::VALIDATION_GROUP_REGISTRATION);
}
}
));
}
The generated JS is as follows:
(function ($) {
"use strict";
var form = $("form[name=\"appbundle_registration\"]");
var validator = form.validate({
...
});
validator.settings.validation_groups = {
"registration": true,
"registration_austria": true,
"registration_switzerland": true,
"registration_italy": true,
"registration_germany": true,
"Default": true
};
})(jQuery);
Do I have to enable/disable to validation groups with an own javascript callback if field country is changed? Is there a preferred way?
User Deprecated: Calling "getfield_dependency" on template "BoekkooiJqueryValidationBundle:Form:conditions.js.twig" from template "BoekkooiJqueryValidationBundle:Form:macros.js.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0.
File: boekkooi-jquery-validation-bundle/src/Resources/views/Form/macros.js.twig
Line: {{ attribute(macro_conditions, condition.macro, [condition, rule]) }}
Hi again
Seems like Regex validation is not working.
I've activated the pattern option in the config but nothing happens in my browser.
I need to ensure the fields firstname and lastname are only letters. The other constraints works.
Here what I obtain in my browser's console :
Perhaps it could help you.
...or do I have to implement the constraint IsTrue by myself? I'm trying to use type checkbox with IsTrue validator to force user to check the terms.
http://symfony.com/doc/current/reference/constraints/IsTrue.html
In jquery validation doc I didn't find that it's supported: http://jqueryvalidation.org/documentation/#link-list-of-built-in-validation-methods
and in additional-methods.js there is no IsTrue method.
{{ form(form, { attr: 'data-rules': form_jquery_validation_rules() }) }}
Hi Boekkooi,
Could you confirm your bundle isn't compatible with jQuery validate 1.11 ?
I have trouble using it with this version (undefined validator methods) and all my problems disappear with jQuery validate 1.13.
Thank you again
Hi, just an suggestion for ui improvement, for now, if input has error, JS show:
<label id="[ID-INPUT-WITH-ERROR]-error" class="error" for="[ID-INPUT-WITH-ERROR]">Cette valeur ne doit pas être vide.</label>
Could you add an option for custom how label with error is rendered.
eg something like that
<div class="alert alert-danger"><ul><li>Cette valeur ne doit pas être vide.</li></ul></div>
Goal, get same error design like if I submit form
--- EDIT ---
just need to use jquery validate options
Hi
I am using collection type with my custom entry_type. It is actually the collection of files for a project. the validation works only for the first item I check in your example where you use tags as collection. In your example in the generated javascript it looks for all the tags ie using .find to find all occurances of collections and then apply the js validation. In my code it is validating the first one mean not using the .find to apply the validation on all collections. Urgent help will be appreciatged.
Hi,
For a very specific case for which I need to validate a field only if an associated checkbox is checked, I've created a custom constraint embedding existing constraints and using my whole object as $value. I don't know if it's the way it should be but it's working as expected.
Here the code of my validator.
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ValidScheduledEndDate) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\ValidScheduledEndDate');
}
if ($value->getIsEndDateScheduled()) {
$validatorBuilder = new ValidatorBuilder();
$validator = $validatorBuilder->getValidator();
$constraintNotBlank = new NotBlank();
$constraintNotBlank->message = $constraint->messageNotBlank;
$constraintDate = new Date();
$constraintDate->message = $constraint->messageDate;
$constraintBeforeNow = new BeforeNow();
$constraintBeforeNow->message = $constraint->messageBeforeNow;
$violations = $validator
->inContext($this->context)
->atPath('scheduledEndDate')
->validate($value->getScheduledEndDate(), array(
$constraintNotBlank,
$constraintDate,
$constraintBeforeNow
))
;
}
}
Do you know if there is a way to create a custom rule mapper for this specific case ?
Thanks.
Hi,
Recently I upgraded my application to sf 2.7 and I'm getting following deprecated messages from debug toolbar, it is a small issue, Before upgrade The original function was "sameas", and "same as" created for an alias but now "same as" is the original and "sameas" deprecated documentation says, so any update shouldn't be break backward compability.
DEPRECATED - Twig Test "sameas" is deprecated. Use "same as" instead in BoekkooiJqueryValidationBundle:Form:macros.js.twig at line 53.
DEPRECATED - Twig Test "sameas" is deprecated. Use "same as" instead in BoekkooiJqueryValidationBundle:Form:conditions.js.twig at line 2.
DEPRECATED - Twig Test "sameas" is deprecated. Use "same as" instead in BoekkooiJqueryValidationBundle:Form:conditions.js.twig at line 9.
DEPRECATED - Twig Test "sameas" is deprecated. Use "same as" instead in BoekkooiJqueryValidationBundle:Form:conditions.js.twig at line 27.
http://symfony.com/doc/current/reference/constraints/Length.html
It's currently not implemented and it would be fine to be able to use it 💃
Let's say I have these two entities:
class Task
{
/**
* @Assert\NotBlank(message="You have to enter a task name")
*/
protected $name;
/**
* @Assert\Valid()
*/
protected $tags;
}
class Tag
{
/**
* @Assert\NotBlank(message="You have to enter a tag name")
*/
protected $name;
}
I also have a Task form which embeds a collection of Tags.
The task name error is displayed correctly, but instead of the tag name error I get the generic "This field is required."
It would be nice if we could have an option to dynamically change the validation_groups to use when validating the form depending on user inputs (i.e. : when using radio inputs)
Hi,
This is an amazing bundle it really saved my days thanks firstly.
My Entity field has the following annotation https://gist.github.com/feyyazesat/aa6674271ce5174041ba
NotBlank and Length working properly. But when I write "xyaz 123" to the field, following errror appears on chrome dev console.
1c0764d-c181255_part_1_jquery.validate_2-2a98529.js:640 Uncaught TypeError: Cannot read property 'test' of null
Do you have any idea about this problem ?
I am trying to use the bundle (master) in connection with a Birthday
form type. During the registration a user should input his birthday. The corresponding part of the form type looks like this:
->add('birthday', 'birthday')
When the page is loaded, the JavaScript console outputs something like this (chrome):
Uncaught TypeError: Cannot read property 'form' of undefined
The use of a standard DateType
like the following works like a charme.
->add('birthday', 'date', array(
'years' => range(date('Y') -90, date('Y')),
))
I thanks for this bundle, but I think it's not works. When I'm enable bundle in AppKernel, I get this message.
Notice: Undefined index:[MYFORMENAME] in /var/www/symfony/vendor/symfony/symfony/src/Symfony/Component/Validator/Mapping/ClassMetadata.php line 390
Form with submit btn doesn't work properly:
Warning: array_filter() expects parameter 1 to be array, null given in [FormRuleContext.php#L29](https://github.com/boekkooi/JqueryValidationBundle/blob/726f34e7c4cef101bf5b6b998346b342b45c42ed/src/Form/FormRuleContext.php#L29)
$builder->add('submit', 'submit');
I think the default value for group should be array and not null normalizeGroups
Is there an overview over supported and unsupported constraints?
Hello,
I have 2 forms.
BecomeHostFormType and BasicUserFormType. I embeded basic_user to become_host form. I configured validations group etc. and my embed method is like following.
$builder
->add('basic_user', new BasicUserFormType(), [
'data' => new PjUser(),
])
;
I use in twig ex: {{ form_widget(form.basic_user.firstname) }}
basit_user form's generated html looks like following.
<label class="block-label" for="become_host_basic_user_firstname">Firstname</label>
<input type="text" id="become_host_basic_user_firstname" name="become_host[basic_user][firstname]" _vkenabled="true" _originaltype="text">
plugin's generated code :
(function($) {
"use strict";
var form = $("form[name=\"become_host\"]");
var validator = form.validate({
rules: {
"become_host\x5Bservices\x5D": {
"required": {
depends: function() {
return (validator.settings.validation_groups["become_host"]);
}
}
}
},
messages: {
"become_host\x5Bservices\x5D": {
"required": "form.become_host.validation.services.blank"
}
}
});
validator.settings.validation_groups = {
"become_host": true,
"Default": true,
"basic_user": true
};
})(jQuery);
and it doein't read firstname's validation rules, but it does read become_host's services field rules.
Do you have any idea to solve this problem ? I have to use this plugin with embeded forms also.
Hi Boekkooi,
When I use a pattern like : /^[a-zA-Z0-9\\u00C0-]+$/
in Symfony constraint, it ends up in javascript in [a-zA-Z\\\\u00C0-]
which is obviously not working.
Do you know any way to use unicode characters in RegExp constraints ?
Thanks
Hi
I'm currently testing your bundle in my application.
I have a strange behaviour with a blank repeated field.
Here is the code to build my form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
'first_name' => 'password',
'second_name' => 'password_repeated'
))
;
}
When I try to validate my form with client-side validation disabled, I got
And with client-side validation enabled :
I understand Symfony doesn't check the repeated field if the main field is blank whereas JQuery does.
Do you know how I can get the same result as Symfony ? Or even having the field considered as not correct.
By the way, I really like this bundle for saving me a lot of time.
Thanks
Unfortunately, client side validation seems not works correctly
I use jQuery v2.1.1n, I have also try with JjQuery v1.11.1
I haved added link to jquery validator
you're twig extension added this in my code :
(function($) { var form = $("form[name=\"fchanal_adminbundle_user_profile\"]");var groups = {"Default": false, "userBasicEntity": false};form.find("*[name=\"fchanal_adminbundle_user_profile\x5BsubmitUserBasicEntity\x5D\"]").click(function() { groups = {"Default": true, "userBasicEntity": true}; }); form.validate({ rules: { }, messages: {} }); })(jQuery);
but nothing happen when I click on submit invalid form
maybe because this is empty?
form.validate({ rules: { }, messages: {} }); }
JqueryValidationBundle is not working with that bundle : https://github.com/lexik/LexikMailerBundle
Error: Call to a member function getConfig() on a non-object
500 Internal Server Error - FatalErrorException
in vendor/boekkooi/jquery-validation-bundle/src/Form/FormDataConstraintFinder.php at line 117 -
}
// If the root inherits data, then grab the parent
if ($dataForm->getConfig()->getInheritData()) {
$dataForm = $dataForm->getParent();
}
CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\FatalErrorException: "Error: Call to a member function getConfig() on a non-object" at C:\wamp\www...\vendor\boekkooi\jquery-validation-bundle\src\Form\FormDataConstraintFinder.php line 117
Stack Trace (Plain Text) -
[1] Symfony\Component\Debug\Exception\FatalErrorException: Error: Call to a member function getConfig() on a non-object
at n/a
in C:\wamp\www...\vendor\boekkooi\jquery-validation-bundle\src\Form\FormDataConstraintFinder.php line 117
How to fix that ? Can I disable the validation on this form only?
when I create a form without name JqueryValidationBundle produces 2 exceptions in:
I made a quick fix for that see my commit
https://github.com/aitboudad/JqueryValidationBundle/commit/da07b54201ff3b452c64e761e64f9970ed884724
$form = $this->get('form.factory')->createNamed('', new SimpleFormType());
Hi,
first of all, thanks for the awesome library.
Is there a plan to fix all the deprecating warnings which are already showing up in sf 2.8.x.
PS: This should also help for easier compatibiliy to sf 3.x, when time comes.
best regards,
horfic
At least:
Not quoting the scalar "%boekkooi.jquery_validation.additional.required_group% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 2x
Not quoting the scalar "%boekkooi.jquery_validation.form.form_extension.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.luhn% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.pattern% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.accept% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.one_or_other%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.ipv6%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.ipv4%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.is_boolean% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.iban% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.enabled%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.additional.time% " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.constraint_finder.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.rule_compiler.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.rule_processor.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.form.button_extension.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Not quoting the scalar "%boekkooi.jquery_validation.twig.jquery_validation.class%" starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0: 1x
Hi Boekkoi,
I can't find a way to make Count constraints work.
Is this constraint implemented ?
I'm using dev-master.
Thanks !
I have a form I build using the following:
$builder
->add('user', UserType::class)
->add('consent', CheckboxType::class, [
'required' => false,
]);
UserType contains a few fields, such as firstName
and lastName
. Both of these fields are required. When I enable this bundle, the required
attributes on the inputs for firstName
and lastName
are removed.
This seems to be happening on ValidConstraintPass
line 34. My form is not bound to an entity and it seems like ValidConstraintPass
checks for Symfony\Component\Validator\Constraints\Valid
on child form elements in the entity.
Do I need to bind my form to an entity and use the @Valid
annotation to get your bundle to work?
Hi, thx for greate bundle :).
I have a problem. I have form which contains another form\forms like this http://symfony.com/doc/current/cookbook/form/form_collections.html . How to validate subforms ?
Everything is in the title
Hi
While I was trying to implement validation for my collection fields, I detected one mistake in the collection sample code you provide in the documentation.
I replaced
{%- set attr = attr|merge({'data-prototype': form_row(prototype) ~ '<script>' ~ form_jquery_validation(form) ~ '
<script>
' }) -%}
by
{%- set attr = attr|merge({'data-prototype': form_row(prototype) ~ '<script>' ~ form_jquery_validation(form) ~ '
</script>
' }) -%}
to make it work.
Do you confirm this is the way it should be ?
form_jquery_validation
replaces the form
method. Can you do this for the other related twig methods like form_start
, form_end
and form_row
?
I would like to add a date validation to my form. I have a field using the formType = birthday. I think I am supposed to follow the directions in custom_constraints.md to add the validation.
I did the following:
creditcardRule.php
to my src/bundle/form/rule dir
and renamed to BirthdateRule.php
.BirthdateRule
return get_class($constraint) === 'Symfony\Component\Validator\Constraints\DateTime';
I am not sure what I need to do next. Can you guide me?
Thank you Very Much for this bundle!
Hi,
It could be nice if we can set the translation domain as parameter in the macro. Line 121 and 123.
I use custom constraint and i'm not in the validator domain, so a parameter for that would be nice.
Thanks in advance.
Thanks for this bundle, it's really useful.
I would like to know how I could use validation groups and buttons with this bundle.
For example, suppose that only part of a form is visible, and there are "next" and "previous" buttons.
How would I be able to do "group validation" on the next button, and all validation on submit?
I tried to just add some additional JS code, but the validator is out of scope since it's encapsulated in a function closure. Could we maybe add the option to have the validator in the global scope?
Hi again :). I have another problem. I'm try to create my custom form type - range. Which allow to create range fields like min_size and max_size.
First, i show the code, for more perception:
Custom Range field type
class RangeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add($options['min_name'], $options['type'], array_merge($options['options'], $options['min_options']));
$builder->add($options['max_name'], $options['type'], array_merge($options['options'], $options['max_options']));
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['min_name'] = $options['min_name'];
$view->vars['max_name'] = $options['max_name'];
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'type' => 'text',
'options' => [],
'min_options' => [],
'max_options' => [],
'min_name' => 'min',
'max_name' => 'max',
'error_bubbling' => false,
]);
$resolver->setAllowedTypes([
'options' => 'array',
'min_options' => 'array',
'max_options' => 'array',
]);
}
public function getName()
{
return 'range';
}
}
Entity for test
class TestRangeEntity
{
/**
* @var int
*
* @ORM\Column(name="min_size", type="integer")
*
* @Assert\NotBlank()
* @Assert\GreaterThanOrEqual(value=400)
*/
private $minSize = 400;
/**
* @var int
*
* @ORM\Column(name="max_size", type="integer")
*
* @Assert\NotBlank()
* @Assert\LessThanOrEqual(value=2000)
*/
private $maxSize = 700;
}
And form for TestRangeEntity
class TestRangeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('size', 'range', [
'virtual' => true, // <- VIRTUAL OPTION
'min_name' => 'min_size',
'max_name' => 'max_size'
]);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => TestRangeEntity::class
));
}
public function getName()
{
return 'test_range';
}
}
Also i'm create custom twig form widget (range_widget) which render this field like this:
<div class="form-range-group">
<input type="text" name="application[size][min_size]" class="min-value form-control" value="400">
<input type="text" id="application-size-max-size" name="application[size][max_size]" class="max-value form-control" value="700">
</div>
In this case, your bundle not created client constraints. How to fix this ?
Why my field 'size' is virtual ? Because if it's not virtual, then symfony try to fill this field, but entity not contained this field, and symfony throw error.
http://symfony.com/doc/current/reference/constraints/Type.html
I don't know if its useful to implement the type constraint but currently I have a field with constraint Type and type is digit. It's for validating zip code.
A workaround would be to use Regex but Type feels better somehow.
So that at least bugfix for #39 (Not able to use Birthday form type) is available in a stable release.
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.