Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing Symfony2 validation rules with backbone.js or javascript in general?

Would it be possible to expose Symfony2 validation rules (for a given Entity)? I can't find anything like this. I'm trying to do client-side validation (using backbone.js) with a DRY approach. Something like a bundle or any tip would help.

Here is the component validator. One possibility would be:

Define server-side validation rules using Symfony2 standard way. Example (YAML, taken from their website):

# src/Acme/BlogBundle/Resources/config/validation.yml
Acme\BlogBundle\Entity\Author:
    properties:
        name:
            - NotBlank: ~

Make /author/rules return a JSON object which maps fields from the entity to a "compiled" regular expression. I'm not so sure about this but I think that internally Symfony2 compiles validation.yml rules into regular expressions.

Assuming an author entity made of name field with NotBlank (note i'm not a master in regex, this is a copy and paste from another question):

{ 'name' : '^\s*\S' }

Finally retrieve that JSON object and do client-side validation with backbone.js system. Possibly do caching. For example (warning! pseudo-code-like code inside validate()):

<script>
    $(function () {
        window.MyApp = window.MyApp || { Models : {}, Views : {}, Router : {} };

        window.MyApp.Models.Author = Backbone.Models.extend({
            initialize : function() { _.bindAll(this, 'validate') },
            validator : $.get('/author/rules');
            validate: function(attrs) {

               // Loop each property of this model
               _.each(attrs, function(field, value) {

                   // Get the regex from the validatior
                   var rule  = this.validator[field];
                   var regex = new RegExp(rule);

                   if(!regex.test(value)) return "Model not valid.";

               }
            }
        });
    });
</script>

Am I asking for the moon?

like image 773
gremo Avatar asked Mar 07 '12 01:03

gremo


1 Answers

You can try this bundle. I've used it with varied success in the past.

https://github.com/formapro/JsFormValidatorBundle

It exports all of the Symfony validation rules and dumps then in to a JS data structure. Then there are various helpers to allow you to enforce these validations. Also remember to disable HTML5 form validation with <form novalidate="novalidate"> etc

I think it may be limited to Symfony <= 2.6 but I've got it working up to Symfony 2.7.7. The maintainers are currently working on Symfony 3.0 support I think.

This bundle is still in active development:

  • Version 1.2 supports Symfony <= 2.6
  • 1.3 for Symfony 2.7 - 2.8
  • 1.4 for 3.0
  • 1.5 for 3.1
  • 1.6 for 4 (although this is currently a pre-release)
like image 71
Benr77 Avatar answered Oct 18 '22 09:10

Benr77