DRY Remote Validation in ASP.NET MVC 3 - validation

I've read David Hayden's great post on MVC 3 Remote validation.
However there is presented what you should do to enable remote (javascript) validation. If the user has javascript disabled the post would still be made even if data is not valid. Therefore a server-side validation should occur.
How could we make this check as DRY (Don't Repeat Yourself) as possible? Of course, including the same check code in the post action as in the remote validation action (or just the same call) can work but I am wondering if a one-liner or something more elegant is available.
Perfectly acceptable answers include "no, it can't be done". :)

See my MSDN article How to: Implement Remote Validation in ASP.NET MVC
I use the remote client validation code in the HttpPost Create method to test server side when JavaScript is disabled.
[HttpPost]
public ActionResult Create(CreateUserModel model) {
// Verify user name for clients who have JavaScript disabled
if (_repository.UserExists(model.UserName)) {
ModelState.AddModelError("UserName", ValidationController.GetAltName(model.UserName, _repository));
return View("Create", model);
}

It 'can' be done.. but you would need to write your own custom attribute that basically emits for client side and is validated server side. For me I just extract the validation code into a method and check on the server.
Something similar came up recently as well:
Prevent form from submitting when using unobtrusive validation in ASP.NET MVC 3
I wonder if one couldnt inherit from the remote attribute and add their own server side code them. hmm.. maybe I'll have to try this.
I would be happy though if someone here said they already did this : )

I have done this, it's a bit of a long solution, so it's all available on my blog here:
http://www.metaltheater.com/tech/technical/fixing-the-remote-validation-attribute/
I had to create a new subclass of the RemoteAttribute class, create my own custom model binder by inheriting from DefaultModelBinder, and then use reflection to call the validator on the controller.

Related

How to stop grails erasing custom validation errors

In my Grails app, I am using methods in a service to do complicated validation for user submitted data. Unfortunately, Grails is quietly sabotaging me.
I populate the domain instance with the user submitted data
I hand the instance off to the service, which analyzes the properties.
If errors are found I add them using
instance.errors.rejectValue('myValue','errors.customErrorCode','Error')
BEHIND THE SCENES, when the service passes the domain instance back to the controller grails checks for changed properties and calls validate() before returning the instance. (verifiable by seeing the beforeValidate event called on returning a domain instance from a service to a controller where one or more properties has changed)
That behavior clears any custom errors I have added and the instance I get back in the controller is now incorrectly without error.
How can I
A) stop grails from validating between service and controller
OR
B) prevent a validate() call from wiping my custom errors.
EDIT
So far I've found one partial answer,
If you use instance.get(params.id), grails will self validate behind the scenes wiping custom errors.
If you use instance.read(params.id) you can bypass this behavior to an extent.docs
But this solution is limited by domain relationships. Any other solutions welcome.
Seems that it is not custom validation. It can be because of transactional service. Service opens separate transaction for each method and clears entities after method end. You can find this mentioned in docs(read the last paragraph of part ). So errors dessappear not because of validation.
Don't know if your service is transactional. But if it is - you can add #NotTransactional annotation to method were you want not to loose errors. And
errors will be saved.
Hope it helped,
Matvei.
Not sure how your code looks like or what is causing the problem, but in any case I strongly suggest implementing custom validators in the domain class or in a command object within the constrains.
Here are some examples from grails docs:
http://docs.grails.org/2.4.0/ref/Constraints/validator.html

Validation and ComplexTypes

I have read BreezeJS documention about validation and ComplexTypes. To my knowledge, there should be no reason for that scenario to work.
We use breeze.directives.js. BreezeJS version is 1.4.14. In our application, Person-entity has property PhoneNumber which is ComplexType. Person-entity is binded to a view in AngularJS app. For validation we used the example from Code Camper SPA. Person-entity gets validated and zValidate works as expected. To our surprise PhoneNumber-complextype gets validated too , but validation errors dont show up. So it seems there's problem with zValidation and ComplexTypes.
Anyone know if it should work ? Or are we just missing something?
Note: DocCode or any other sample didn't include this scenario implemented.
zValidate was not written to support ComplexTypes. zValidate is part proof-of-concept and part invitation to the community to contribute. It demonstrates one way to expose Breeze validation to the UI, declaratively, with an Angular directive. We invite you to fork it and offer improvements or alternatives. We're eager to tell the world about your work :-)

Redirecting back to Portlet from ResourceMapping in Spring 3 portlets

I am trying to work out a way to provide a CSV download through a Spring 3 Portlet. I have a method that uses the #ResourceMapping annotation to define a handler that takes some report params in the form of a #ModelAttribute, builds the report, and returns it. The catch-22 I am running into is validating the parameters being send in from the client form.
If I make the handler a #ResourceMapping, I can set the headers and write out the report as using the ResourceResponse, but I can't seem to figure out how to redirect the user back to the Portlet view with errors when their input fails validation. However, if I make it an #ActionMapping, I can then check the BindingResults and forward them back to the form as needed, but the ActionResponse doesn't allow me to set the Content-Disposition header nor write out the CSV bytes, which is sort of critical for sending the report back.
I am at a total loss here, as I don't even know what my options are. Is it even possible to do what I am trying to do with a Portlet? Are there other examples I could look at for a possible work-around?
I suggest you to use both #ActionMapping and #ResourceMapping to fulfill your requirement.
As you said you were able to handle the validation errors using the #ActionResponse, I'll tell you how to handle the Resource Streaming.
As you know every #ActionResponse is followed by a #RenderResponse, just return the same view but, with a hidden iframe this time whose src points to the ResourceURL.
Now the Request you receive in #ResourceMapping is something which is already Validated. So, you can now serve your CSV.
I dont know how complex is your UI and if you are using jsp as views in your application. If nicely managed, Validation can be handled by #ResourceMapping.
Thank you

MVC3 is valid email

Is there a built in function which will test if an email address is valid?
I want to test the email address structure is valid before sending a confirmation email to the end user.
I understand i could create my own function easy enough with the use of a regular expression but if there is a built in function i would much rather use this.
You can do this with Data Annotations extensions I believe. Check out Scott Guthrie's blog post on it here: http://weblogs.asp.net/srkirkland/archive/2011/02/23/introducing-data-annotations-extensions.aspx.
There is a good point in Scott's post as to why you would use this rather than the MVC 3 Futures validators which might be relevant to your choice:
ASP.NET MVC 3 futures defines four new data annotations attributes which this project has as well: CreditCard, Email, Url and EqualTo. Unfortunately referencing MVC 3 futures necessitates taking an dependency on MVC 3 in your model layer, which may be unadvisable in a multi-tiered project. Data Annotations Extensions keeps the server and client side libraries separate so using the project’s validation attributes don’t require you to take any additional dependencies in your model layer which still allowing for the rich client validation experience if you are using MVC 3.
Yes, you can use
public class CustomerMetaData
{
// Add type information.
[DataType(DataType.EmailAddress)]
public object EmailAddress;
}
on your model. See more about it here.
however, last time I checked it does not work client sided.
I googled it, and from imran baloch's blog post it seems it does work now.

MVC3 Architecture/Validation Question

I think this is a pretty simple task, but I can't for the life of me get it working.
Environment - MVC3, FluentValidation, StructureMap.
I have a ViewModel (RegisterViewModel) that has the following attributes { Email, IsBusiness, BusinessContact }. Email is required always, BusinessContact is required if the IsBusiness checkbox is checked.
I was trying to perform the BusinessContact required check client side, but can't for the life of me figure out the right way to do this.
Suggestions?
You will have to roll your own client side validation to enforce the constraint your looking for. Phil Haack has a great post on how to do this http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
Otherwise you could just enforce the constraint server side and add an error to the ModalState and reload the view.

Resources