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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With