Web API - how to have custom display name for model validation properties? - asp.net-web-api

If I have an ApiController which has a post method which consumes a model which has data annotations for validation, how do I customize the name displayed for the validation errors? I don't really want to override the entire error message, but I do need the property in the error to be something other than the name of the property on the model type.
I've tried things like DisplayNameAttribute and DisplayAttribute, but those don't seem to apply for this.

The best solution I found for this was based on the following:
https://gist.github.com/benfoster/4016852
You have to create your own validator provider (as shown in link), and your own validator which will set up a ValidationContext with the proper displayName such that
validationContext.DisplayName = displayNameMappingFunction(metadata.GetDisplayName());
You then need to register the validator provider globally by using GlobalConfiguration.Services, or you need to create an IControllerConfigurationAttribute which will configure it just for one controller.
You do config.Services.Replace(typeof(ModelValidatorProvider), new CustomDisplayNameProvider()

Related

Java Bean Validation - Intercepting Validations

I have the following scenario: I am trying to process a form and the model attribute is a bean with String and Long properties. As you all guys know, bean validation offers a lot of annotation to help us determine the validity of the data.
What I am facing is that, for the case of the Long attributes, I can only use #NotNull and another annotation (I dont recall its name) to force the user to enter positive numbers. If the user enters for instance "sdf", the application throws a BIG exception. So what I would like to know is If I can intercept the form processing and validate by my own if the user entered a numeric thing before it explodes (because I cant use #Pattern)... and I cant switch that attribute to String...
Was it clear ?.
Use Spring Custom validation. That is Annotation-based validation and you have the ability to create your own custom validation logic. Spring Custom Validation In this link you can find out more examples and how to use it.

Custom authorization per action call in Web API

I need to grant permissions for users to call exact actions. And also each permission rule can contain validation rules for action arguments:
[CustomAuth]
public MyController : ApiController
{
[ValidateAccess, ActionName("Myaction")]
public void MyAction([MyTypeAccess] MyType myType)
{
}
}
In my logic i need to check can user call this action and can he call this action with passed MyType value (custom validation).
At the moment i dont see how to get attributes from custom AuthorizeAttribute and i see the solution with Castle interceptors, i'm using for my another purposes (from invocation info)..
Is there a standard way to implement this custom authorization?
Didn't find any direct solution in Web API for this issue.
As i'm using Castle interceptors, i've added a new interceptor on all controllers, which are support auth. Interceptor provide access to invocation and you can retrieve any attribute and value passed to the controller/action.
Validation attribute on an action says you need to apply validation routines on this call, ActionName identifies the type of call (if necessary, in a future this will be moved to an own attribute as action name can differ in legacy controllers for old versions).
If you need to validate action parameters there set of attributes you can use, which identify the type of argument and validation algorithm.

Validation on an external model object using play framework 1.2.5

I have a model object which is defined outside of my play application, it is an auto-generated entity produced from wsdl. This means that I can't reliably add validation annotations to its fields. I thought about extending the class and in fact that's what I've done, and I wonder if its possible to add validation tags to the extended version? An immediate problem that I see with that however is that it also has children who's members would also need validation tags added, and if i were to extend them, they would not be used by play's binder. I guess what I need is some kind of custom validator, but from what I can see they are aimed at validation single properties, not entire object models.
Any pointers or suggestions would be great
Cheers!
NFV
You could write custom validator for your class and use:
public static void myController(#CheckWith(MyValidator.class) myParameter)
in controller to test if objects are valid. Then just manually validate them inside MyValidator (it has to extend play.data.validation.Check).
Check play documentation for more info about custom validators.

Extending JSF validation in application

We are developing a web application based on JSF (v2.0) framework. We need to have custom validations in our application. We decided to extend the JSF validation framework by implementing the Validator class.
So let us say that we have multiple input fields which needs to be validated. These input fields are First Name, Last Name, Email Address. We need the user to enter information in these fields. And email address field will have two validations - Required and isValidEmailAddress.
We should be able to use the custom Required validation in First Name, Last Name and Email Address fields. But each time I want different error messages to be displayed for each field. For example in case of First Name, I want to display First Nameis required. In case ofLast nameI want to displayLast name is required`.
How can I reuse the same Required validation implementation for multiple fields but with different error message? Is it possible to do that in JSF? Could you please let me know?
First of all, you don't need to write your own validation logic for required input in JSF. It's one of the basic amenities provided by the framework itself.
JSF's validation framework is cleanly abstracted from messages related to validation, so the two don't have to depend on each other. Your options:
Each input component has a validatorMessage attribute that allows you specify the text/string that will be displayed to the user on validation error. For your specific use case, JSF has gone one step further to specify the required and requiredMessage attribute for input components; to enforce required input and show messages specifically for required input validation respectively. What this means in your use case is that you don't need to write custom validation logic for required input.
By principle of better design you can configure all your desired validation/conversion error messages in a resource bundle (example here) and reference the entries in the resource bundle within your jsf view.
Implementing the validator interface requires you implement the validate method with the following signature
public void validate(FacesContext ctxt, UIComponent comp, Object value) throws ValidatorException
comp refers to the component being validated from which you can get it's Class, clientId etc. value will provide the submitted value from the component

Custom validation message

I have a problem with validating some data types.
There are int, short, DateTime and so on except string.
Suppose i have following property in my view model class
public int? LineNumber { get; set; }
When i input incorrect value i get mvc error "The value 'balblabl' is not valid for LineNumber."
But what if i want just out something like "Value incorrect"? Or what if i want to use other language? I have no idea how to do it(of course i can use string instead of int but it is painfull workaround)
i already tried dataannotationsextensions [DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")] attribute. It is not working. I cannt to use custom validation attribute because of after binder convertation i get null value in all cases with incorrect value. I just cannt to do my own validation. I can to write my own binder but it looks like a joke. Really i think custom validation message is one of must have featerus and i cannt belive asp.net mvc doesnt has a simple way to do it.
I would like to add another, in my opinion, easy way to add and maintain custom error messages.
using the FluentValidation NuGet package.
It hooks up with mvc pretty easy have a look here
You can easily specify numerous rules for your models and display custom error messages that can use a resource file an example:
public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand>
{
public CreateAgendaPointCommandValidator()
{
RuleFor(cmd => cmd.price)
.NotEmpty()
.WithMessage(Translations.CreateProduct_Price)
}
}
}
Documentation: FluentValidationDocumentation
Those errors are automatically added by the default model binder when it cannot parse the input string into its destination type. They are not like data annotations, where you can specify a resource instead of a harcoded string error message.
However you can use your own resource files, see this other question. Once you have created the resource file, you will update the global.asax for the default model binder to use it:
DefaultModelBinder.ResourceClassKey = "MyResources";
After a custom resource file has been set in the property ResourceClassKey of the default model binder, values will be resolved according to the following criteria (as per the MSDN):
If the property is not set, MVC uses the standard MVC resources.
If the property is set to an invalid class key (such as a resource
file that does not exist), MVC throws an exception.
If the property is set and the class key exists but the resource
names in the file do not exist in the application, MVC uses the
standard MVC resources.
If the property is set and the specified resources are available,
MVC uses the resources in the file.
If you need to know the key values for a particular message check this. For the message The value '{0}' is not valid for {1}., you will need to add a value with the key DefaultModelBinder_ValueInvalid

Resources