Using jqgrid, what is the best way to return errors from server side validation when using inline editing? - validation

I am using jqgrid and using the inline editing mode and can't figure out how to return errors back to the client from server side validation rules
I use fluent validation on my serverside to validate before persisting to a database. This works great except I don't see how to return errors when editing in inline mode. If I don't persist the values to the databse, the client still shows the value which should be rejected.
What is the recommended way to return an error after someone commits an inline edit so you will get some popup on the client side showing the error and it will stay in edit state ?
NOTE: this image below is in response to Oleg's comment and answer below

The recommend way is to use any HTTP error code in the response on the submitting of wrong data and to return the error description in the body of the response. If you need some more specific action like displaying another dialog with the error information, setting of focus on a field, marking some fields with CSS class 'ui-state-error' or something like that you should use errorfunc callback function.
If restoreAfterError is false the inline editing will be continued.
UPDATED: I mention in comments that the server should produce the error message as the response. In case of ASP.NET MVC the default message is HTML text which you posted as the first picture. If you use HandleJsonExceptionAttribute which I described in my old answer the error message will be serialized as JSON, but it contains additional information which you don't need to display (like the StackTrace). So you should use errorfunc parameter of editRow or saveRow to decode the server response. You can either use decodeErrorMessage from the already referenced answer or use the $.parseJSON function directly:
errorfunc: function(rowid, res) {
var errorText = $.parseJSON(res.responseText).Message;
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + errorText + '</div>',
$.jgrid.edit.bClose,
{buttonalign: 'right'});
}

Related

Symfony2 : Best way to check form, client side

I'm developing a form with Symfony2 : several text inputs and one file input (for one picture). I have defined some asserts (maxLength, minLength...) in my entity in order to check the form (isValid).
My problem is : if the user puts bad data in text input (text too long or too short...), he still can submit the form, and error and printed but the user have to re-choose his picture.
As I think it's impossible to keep the picture in the form after bad validation, I should maybe check the form in client side (javascript), before submit.
So, is there an automatic way to do this (to forbidden submit until data are correct)? Can we get the assert minLength, maxLength value in twig ?
Thank you !
Ben.
You can use js validation before submitting the data, using some js form validation tools, but this way you need the replicate the validation logic from the server, so if validation rules changes, you need to modify on both server and client side. I recommend this method to reduce the traffic between client-server.
If you don't want this, use ajax form submitting (example here). You still validate the form using symfony, but the page won't refresh, so you won't lose the attached file. But this generates additional traffic to server, and you also need to implement error displaying using javascript.

Displaying model state errors after ajax call on Razor views

I have razor view with #Html.ValidationMessageFor helpers and jquery unobtrusive validation setup.
I want to call controller/action and to show eventual model state errors returned by action by using same validation logic that is already set in place.
I've made some code that does it but I was wondering if there is already way to do it automatically, i.e. if I capture HTTP Bad Request as AJAX response, I want to take out model state errors from response body and plug them in to unobtrusive validation.
I'm looking for complete recommended solution, not workarounds :)
Thanks!
You can return errors with Json result (How to get all Errors from asp.net mvc modelState?):
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
Then manually show errors. Get form validator:
var validator = $("form").validate();
Then check that your fields are initialized correctly, for example you can look here (optional step):
validator.settings.rules
OR
validator.settings.messages
If everything is fine, then you could show error:
validator.showErrors({"Password": "Too simple!"});
Where Password is field name and Too simple! is error message.

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"})

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

Validate data from CakePHP form with jQuery (AJAX)

I would like to validate both single field and multiple field data from a CakePHP form.
The single field validation should be done on blur from each field while the multiple field validation should be done on submitting the form.
I would like to use the $validate property declared in the Model for validating data and I would like to display the errors near each field (single field validation) and on top of the form (for multiple field validation).
My main goal is to achieve this the most "caky" way (if there is one for validating data with jQuery). I couldn't find any useful advice out there and I'm asking you for some help to get this going.
One of my concerns is how shall I pass data from the form to jQuery and then to the action that does the validation and also how shall I return and display the errors, if there are any.
Thank you in advance!
I'd suggest first making sure everything works without jQuery, then use the jQuery Form plugin to submit your forms via AJAX. If you include the RequestHandler component in your AppController, you should find that your controllers distinguish automatically between AJAX and synchronous requests.
OK, so I coded my own solution to this, but I am still waiting for a more "caky" approach.
I made two generic jQuery functions, one for single field validation and one for multiple field validation. The function should grab the data from the specified form and send it to the form's action via AJAX, to a specially created controller method which will attempt to validate data and output an AJAX response ("" for validation has passed and errors for errors in validation). Then, the result is checked in the jQuery function and the default form behaviour is triggered only if the validation has passed. Otherwise, display the errors and return false; to prevent default submission.

Resources