I think it would be very useful to create client side form validation up on the symfony2 Form
and Validator
components.
The best way to do this would be to pass the validation constraints to the form view. With that information it would be possible to make a template that renders a form field to something like this:
<div>
<label for="form_email">E-Mail</label>
<input
id="form_email" type="text" name="form[email]" value=""
data-validation-constraints='{"NotBlank":{},"MinLength":{"limit":6}}'
/>
</div>
The JavaScript part then would be to find all <input>
elements that have the data-validation-constraints
attribute and create the correct validation for them.
To pass the validation constraints to the form view i thought the best way would be to create a form type extension. That's the point of my Question: Is this the correct way? And how is this possible?
At the Moment my form type extension looks like this:
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormBuilder;
class FieldTypeExtension extends \Symfony\Component\Form\AbstractTypeExtension{
public function getExtendedType(){
return 'field';
}
public function buildView(FormView $view, FormInterface $form)
{
// at this point i didn't find a way to get the
// validation constraints out of the $form
// the `getAllValidationConstraints` here is just an example
$view->set('validation_constraints', $form->getAllValidationConstraints());
}
}
How can i get all validation constraints applied to one form field out of the FormInterface object?
Doing input validation on both the client side and server side has a number of benefits: It helps reduce server load since invalid data is never submitted in the first place. It helps prevent malicious users from submitting invalid data.
With the help of server-side validation, we can get protection against malicious users. On the other hand, the user input validation that takes place on the client side is called client-side validation. Scripting languages such as JavaScript and VBScript are used for client-side validation.
When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation.
Server-side validation is slower than client-side input validation. However, server-side input validation is more reliable than client-side input validation. Thus, it's safe to say that client-side data validation improves user experience while server-side input validation improves security.
Check the corresponding open issue "[Form] JavaScript validation" which contains a reference to SimpleThingsFormExtraBundle (or rather a specific, open PR of that bundle) that does that.
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