User-friendly message for when user enters html - asp.net-mvc-3

Have an ASP.NET MVC3 app with model validation using FluentValidation. User enters some html in a regular text field, and is presented with a user-friendly error on submit (because of the "A potentially dangerous Request.Form value" error).
What I'd really like to do is show a validation message right on the form itself ("Oops, no html allowed") which shows up right next to the field - similar to model validation errors. That way, the user (malicious or not), knows about it before the entire form is actually filled out and submitted.
Would appreciate any ideas on how to go about implementing this apart from what's shown here (i.e. without having to add [AllowHtml] + a regex to almost every field in almost every viewmodel)
Thanks!

You will need to write a custom ProertyValidator for server-side FluentValidation with client-side support. I think you can follow this article, here, to create client-side jquery validation rule and the adapter.

Related

how to display validation errors on submit with Formik?

Very weird thing that Formik seems to be so famous but I can't find this very simple functionnality.
Lets say the user try to send the form with an empty field, how can I display the errors ? I can display them once the field is touched but not once the form has been sent (and obviously I don't want to display the errors right away, for example an empty field)
The actual behavior is that the submit function is not called if the validation fails, seems right but what about error display ? It seems there is no simple way to do this (I found a few kinda heavy work around with some callbacks and handler components but what's the point using a form library then...)
So maybe I have missed something please tell me
Any idea how to display the validation errors when submitting the form ?

yii ajax renderpartial with form validation

I have a dropdown list in yii that depending on the id renders some additional fields (that requests other models).
How can I use the $form field in those (it's Yii-Bootstrap) so that I can have the validation messages (via $form->errorSummary() ) and not implementing my own javascript messages?
I'm not entirely sure what your asking for, but it seems like it's related to rendering form fields/errors and validation. As far as specifing custom selector fields goes, look into CHthml::activeDropDownList, it'll let you define your drop list items accordingly. As for validation, you can validate that drop down by making it have it's own validation rule and error as described here:Custom Model Validators. This will allow you to use CHtml::errorSummary($model) as the dropdown will return an appropriate error message if it's validation fails...
Cheers,
Fy
Not sure if this helps, but renderPartial() has serious issues with AJAX:
http://www.yiiframework.com/forum/index.php?/topic/10427-ajax-clientscript

MVC 3 Razor-Partial Validation of Model

I am currently working on a project in MVC 3 where I am leveraging Entity Framework to persist one data model over two Views which each contain one HTML Form (similar to wizard-based design).
Yet after the user fills out the appropriate fields on the first View and submits the form, client-side validation for the entire model is triggered, and validation errors are shown for fields that will not even be available for input until the second View instantiates.
I have currently implemented a workaround where I simply turn off client-side validation for the first View entirely, but I am certainly not keen on the idea of populating my model with data that has not been validated at all. This is bad. M'kay.
Is there any way to partially validate the fields on the first View and not trigger valdiation for the whole data model?
That's where ViewModels comes. Instead of directly binding the domain model with the views, you should create view models over them and bind to the views.
If you are not required to put validation on the EF models directly then you can use the MetadataType to do partial validation as needed. Take a look at my long example here on stackoverflow.
Thanks for the input all. However, I was able to obtain a solution in a very simple way. By placing the following code in the HttpPost element of the first View...
if (ModelState.IsValidField("FirstField") && ModelState.IsValidField("SecondField"))
return RedirectToAction ("NameOfAction", model);
else
return View();
...I was able to achieve partial field validation. However, this field-specific approach will ONLY work provided the Submit button on the first View has class "cancel" and the additional validation errors that are generated (for the fields that are NOT present on the first View) are manually cleared before the above if statement. To do this, use:
ModelState["FieldName"].Errors.Clear();
No major change in architecure. No partial Views. No handing off unvalidated Data.
Works very well...
NOTE: If the second View loads with validation errors, use:
ModelState.Clear();
in the Action where the second View is initially called. This will make the second View load clean and error free, while still showing the validation errors later upon final form submission.

MVC3 selectively validate client side

Each form in the application has a set of radiobuttons. Once selected, only certain fields associated with that radiobutton will need to be validated.
I am using MVC 3 and need the validation to work client side.
Simply using DataAnnotations I can only validate all fields on the form.
IValidatableObject doesn't work clientside.
IClientValidatable looks like it might do the job, but it seems I would have to write a new attribute for every standard DataAnnotation attribute.
RemoteValidation works with one field at a time.
Another option would be to drop MVC3 validation and do it all using jQuery. I don't have a problem with this as such but would like to use MVC3 and reduce coding/maintenance in preparation for a much larger project.
Could I still use MVC3 validation but then use jQuery to add/remove validation fields from validation whenever a radiobutton is selected?
If anyone can help with some suggestions as to the best way to approach this, it would be much appreciated.
MVC 3 uses jQuery's validation plug-in by default and that plug-in will not validate disabled fields. Are the fields that you don't want to validate no longer needed if certain radio buttons are selected? If so, then you can just disable those elements and they won't be validated (and note that those disabled fields won't be posted to the server either).
e.g.
$('input').attr('disabled', 'disabled');
For complex validation it is best to hand code these.
Data Annotations work great for 90% of your validation needs, but fail dismally with What/If scenarios.
For the client side use an event driven custom validation presented via jQuery Validation Plugin. For the server, use the CustomValidation attribute:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx
Using IClientValidatable is great if you have reusable custom validation, however it is wasted time for one off validations.
Alternatively use RemotValidation with a CustomValidation attribute that invalidates multiple fields.

How do I process a complex graphical UI element in a django form?

I have a few complex GUI elements (like a custom calendar with many days that can be highlighted) that appear along with standard django form input fields. I want to process the data I/O from these complex forms along with the Django forms.
Previously I would use AJAX requests to process these custom GUI elements on my HTML form after the Django form was saved or rendered, but this leads to a host of problem and customized AJAX coding. What is a good way to handle complex interactions widgets in a Django form?
Not sure if I understand completely, but you could have the value of your UI saved into a hidden element on the form via javascript. This can either be done as they select the values in the UI or when they submit the form. Pseudo-code assuming JQuery using submit() to save before the submit data is sent:
$('#myForm').submit(function(){
// get the value of your UI
var calendarValue = calendarWidget.getValue()
// #calendarData is the hidden field
$('#calendarData').val(calendarValue)
})
This obviously requires JS, but so does using your UI element.
Your question is very vague so I suggest you read the Django documentation on writing a custom field and hopefully that will help you get started. You might also want to investigate writing a custom widget. Unfortunately the documentation is bit lacking on that, but a Google search brings up several useful blog posts, including this one.
You have three options depending on how you output your Django Form subclass to the HTML page.
The first doesn't involve Form at all. Any html form inputs will end up in request.POST, so you can access them there. True, they won't be bound to your Form subclass, so you would have to manually inject the value either using a custom form constructor, or by setting some property on your Form object after instantiating it with request.POST. This is probably the least desirable option, but I mention it in case your use-case really doesn't support anything else.
The second is an option if you manually output the form fields in your HTML (ie: using {{ myform.field }} rather than just {{ myform }}. In this case, make a hidden variable to contain the value of your calendar GUI tool (chances are, your GUI tools already offer/require one). Add this hidden field, with the right name and ID, to the Form subclass itself, making sure it has a hidden django form widget. If necessary, use javascript as Rob suggests to populate the hidden field. When the form is posted, it will get bound to your form subclass as normal because, this time, you have a field on your Form subclass with that name. The machinery for clean() will work as normal.
The third, and best option, is to write a custom django field; Andrew's post has the link. Django fields have the ability to specify js and css requirements, so you can automatically encapsulate these dependencies for any page that uses your calendar widget.

Resources