How to share validation rules of several models and a large ajax form that holds them - ajax

I have a large ajax managed form with several steps. Obviously, I need to validate data after each submit step. The final validation results in the creation of several business objects.
Some business objects will receive all of their fields, others will not. For example, the customer who will not receive the billing address (it will be requested at the time the billing takes place). Indeed, the form being very long, I do not want to overload it by adding elements not immediately useful.
Some form partial concern only few informations
hold by my model so i can't instanciate model just for validation of little % of his attributes.
In principe, with October, the validation is done at the level of the models by adding the trait validator which will make it possible to use the generic Laravel validation functionalities (perhaps i'm wrong here)
But I'm not sure I can use on the models validation because some will be incomplete at the end of the form filling.
It is necessary to mutualize the validation of all these data without making a gas factory with duplicate validation code but how, where?
For the moment I am on the idea of ​​making a trait added to my object component which handles all my ajax handlers but I am not excited because it does not correspond to my idea to mutualize the validation
Perhaps using behavior instead of traits are better
https://octobercms.com/docs/services/behaviors
to be continued ...

If I had to do it, I'll use the Validation service after each submit step.
https://octobercms.com/docs/services/validation
You can store the info in a session and use them at the final stage.
$myinput = post('myinput');
$validator = Validator::make(
[
'myinput' => $myinput
],
[
'myinput' => 'required|min:8'
]
);
if ($validator->fails()) {
// The given data did not pass validation
}
// store in session
Session::push('myform.myinput', $myinput);
Session::push('myform.step', 2);
PS: on est deux francophones qui se causent en anglais :)

Related

Symfony Good practice : How to embed several forms for a single entity, handled by different controllers

I'm working on an application with Symfony 2 and I'm quite new with this framework.
I would like to create a page that represent an user profile on which users can update their personal information, set up an profile picture and a cover picture.
I've written the code for the User class and the template. For both profile and cover picture i'm using ajax with formdata to send images to server.
The other fields (username, email, etc.) are also sent with ajax, but all three parts (profile picture, cover picture, textual fields) of the form have their own submit button.
My problem is about creating controllers and forms.
Should I create a controller for rendering the profile page and then one controller for handling the form ?
Should I create a single form for all fields on the page or create three separated forms that would be handled separately ?
Should I use formbuilder to create form(s) and in the case of there are more than a single controller, how to retrieve the form created in the first controller in the others to proceed validation
Or maybe am I wrong from the beginning ... ?
I can provide my current code, but I don't think it can be useful since my User class and my template are very basic and I'm stuck on writing the rest of the code ; and I prefer knowing the "good" way of doing it before writing too much trash code.
You can have many form and validate them in one controller:
public function updateAction(Request $request)
{
$form_one = $this->get('form.factory')
->createNamedBuilder('form_one', 'form')
->add('user_picture', 'file')
->add('submit', 'submit')
->getForm()
->handleRequest($request);
// Next form ...
if ($form_one->isValid())
{
// Save user picture
$data = 'user picture saved';
}
// Other forms validation
return new JsonResponse(data);
}
Make sure to create the same forms in user profile controller view.
Should I use formbuilder to create form(s) and in the case of there
are more than a single controller, how to retrieve the form created in
the first controller in the others to proceed validation
You could make formType, like in this example, there is RegistrationType.
Then use formType in different controllers.
Then you could validate form from entity(or whatever doctrine,propel or whatever you are using) using entity validators
You could also check generator bundle, specially Generating a New Form Type Class Based on a Doctrine Entity
Symfony best practices say to use custom form type classes for forms
link
I always use seperate controller actions for seperate forms. Code becomes more organized and is easier to debug. And I have had issues/bugs with multiple forms in same controller.

Laravel validator vs requests

Hello,
I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get.
What is the difference between using a request file for validation or the validator class ?
If I have validation conditions, and I want to use them only if the concerned field was submitted, how can I do that ? If I use the "required" keyword, it won't work because it will fail when the field is not submitted. If I don't use it, it will accept empty strings...
Thanks ahead !
1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate, then it would be overkill to use FormRequest. So it is a matter of preferance.
2. You don't have to use 'required' if the field is not required. Other validation for that field will still run if that field is submitted. If not submitted nothing will happen.
.......
'money' => 'numeric',
.......
Above Rule will make sure that money field is numeric only if it is submitted. If no submitted no validation error will be thrown.
I hope this helps.
Request classes are the better way to validate requests, because
they help to extract this functionality from the constructor method,
which should be as clean as possible.
Use 'sometimes' validator. http://laravel.com/docs/5.1/validation#conditionally-adding-rules

How I can validate only some validation groups based on some fields in the form itself in Symfony2

I have a big form organized in some validations groups. For every group in the form there is a corresponding checkbox which tell the server to save group data.
When the user post the form, I need to validate only validation groups whose correspond the checked checkboxes because some of their "sub" fields are required, but only if you activate the group. Otherwise the validator must ignore the required fields.
Actually I do that in my controller. I skip the Symfony's normal validation cycle and manually I validate every field checking for the group activation checkbox.
How I can move this validation logic inside the Form class or in a specific Constraint class used by the entity?
EDIT:
As said below is possibile in symfony 2.1, for now i solved:
$request = $this->get('request');
// myEntity knows the business logic to chose validation groups
$myEntity->collectValidationGroups($request);
$form = $this->createForm(new MyEntityType(), $myEntity);
If you are using Symfony 2.1 then you can set validation group based on submitted data. Check this section.
There is another possibilty than the one offered by 2.1.
You can set the validation_groups attribute on the form using $builder->getData():
// inside buildForm method of a form type:
$builder->setAttribute('validation_groups', $builder->getData()->getValidationGroups());

asp.net mvc 3 jquery adding validation message manually

I've been search for quite a while and haven't been able to find an answer to this.
I am using asp.net MVC 3 with unobtrusive validation. My model is bound with data annotations for simple validation (required fields, regex, etc..). However, I have more complex validation that occurs on the server. I'm doing an ajax post which returns me validation add'l messages that come from my domain model. All I want to do is put those validation messages on the form in the place of the existing ones. I don't want to use partial views since all I've really got are messages coming back and there isn't a need to refresh the whole view. Also, I'm not adding new rules or new inputs to the form so $.validator.unobtrusive.parse won't work. These are just messages I want to put on the form. The $.post call returns a list of message with which field is/was affected and the validation message.
Here's kind of what I'm looking to do
$.post(url, { someData}, function (data) {
for (message in data.Messages) {
$("#form").validate().addMessage(message.Field, message.Text);
}
});
Thanks for your help
Per request, here's a sample of the returning JSON, it's fairly simple.
{"id":0,"messages":["Level":0,"Message":"Style is required","Name":"Style"}],"operationResult":false}
messages is a list of objects that contain the severity level, the property the error belonged to and the error message. I would use the name in the messages object to match where it want on the form.
I had exactly the same requirement, I actually found the following method.
var validator = $("form").validate();
validator.showErrors({field : "Error Message"})

In a MVC-model, whose responsibility is it to sanitize input?

A simple question: I have a Model-View-Controller setup, with Models accessing a SQL database. In which part should I sanitize/check for malformed incoming data?
It's important to keep error handling as low as possible in the stack, but supplemental in other parts. If you keep the sanitizing in the controller, you could break the model by swapping out the controller with a looser one, but you can never break the model by being strict higher up in the stack. Keep the sanitizing low in the stack for consistency, and high in the stack for user feedback.
I'd say the Controller should sanitize input.
The model should at most decline to store invalid data.
I would say it is the responsibility of the controller to validate the input and make sure the data is valid before passing on the data to the model.
If invalid data is found, the controller should redirect back to the view and display the relevant error messages.
Having validation in the view only could be bypassed if the user doesn't have javascript enabled or posts to the url directly, however some validation in the view is better from a user experience point of view since the user does not need to wait for a return from the server in a web application.
The model will validate business logic rules, i.e. password length requirements, if a user is allowed to perform an action or not.
The model should obviously also make sure interaction with the database is done in a safe way so that SQL Injection is not possible.
The controller should handle relaying business logic errors back to the view, but can also do some basic sanity checks, i.e. a field is not empty.
I would say output sanitization should also go in the Controller before being passed to the View.
I use two levels of checking. My controller will check what is supposed to be a date is a date, an int an int and so forth. Basically ensuring they can be used to set the values on my objects.
Then my domain has validation for things such as valid values and other business rules. These are ALWAYS checked before saving or interacting with an edited object.
All errors from either level get returned to the user so they can take remedial action as necessary.
I tend to:
Put syntactic validation in the view ("this field is numeric", "that field is a date"). This is often very easy or even implicit in your choice of view design (eg: using a date picker for date fields).
Put semantic violation in a separate validator class ("this date field has to be after that date field", "this can be null if that is greater than zero") and call the validator from the controller, passing errors back to the view for display.
(for my own pseudo-correct definitions of syntax and semantics...)

Resources