How to create custom nested validator with JSR 303? - hibernate-validator

I am using Hibernate Validator - 5.2.2 (JSR 303).
I am doing a cross field validation, so I need to create a custom validator.
However I have no idea how to do the custom conditional nested validation.
example:
#ValidChildrenIfEnabled
public class MainDto {
public boolean isEnabled;
public List<Child> children;
}
public class Child {
#NotBlank
public String name;
#Range(min = 1, max = 3)
public int age;
}
If I don't need conditional validation, I would put
#Valid on top of "children".
#Valid
public List<Child> children;
Note: I know how to create a custom validator, I just don't know how to create a custom validator that do nested validation that take advantage of existing built-in validator. Thanks!
EDIT:
My payload actually has one more payload, let's say SuperDto.
public class SuperDto {
#Valid
public List<MainDto> mainDtos;
}
And I do validation like this:
validator.validate(superDto);

Interesting use case. Unfortunately, I don't think you can do what you want to do as you can't trigger a validation from isValid().
Supposing that you have other constraints you want to validate in every cases, I think the best workaround is probably to use groups. And to use different groups depending of if isEnabled is true or not.
Anyway, you would have to special case how this bean is validated.

Related

Bean validation: method constraints and groups

I use Java EE7 with Bean validations.
I have session bean with a method, where I have defined validation constraints.
public void doTest(#NotNull #Valid Media param1) {
// do something
}
Class Mediahas defined some constraint with groups. Is it possible to validate call of method doTestonly for specific groups?
I found solution with standard annotations. It uses #ConvertGroup.
Working example is:
public void doTest(
#NotNull #Valid
#ConvertGroup(from = Default.class, to = TestGroup.class)
Media param1) {
// do something
}
TestGroup is defined on some constraints inside Media class.
The standard java #Valid annotation can not validate groups. But spring has #Validated that can do. Have a look on this answer.
How to specify validation group for #Valid?.

How to require parameters in asp.net actions

How to require/validate parameters for actions. Right now I have lot of actions that looks like this (which is horrible):
public ActionResult DoSomething(string paramA, string paramB, string paramC)
{
if (string.IsNullOrWhiteSpace(paramA))
{
return JsonResult(false, "paramA is missing");
}
if (string.IsNullOrWhiteSpace(paramB))
{
return JsonResult(false, "paramB is missing");
}
if (string.IsNullOrWhiteSpace(paramC))
{
return JsonResult(false, "paramC is missing");
}
//Actual Code
}
How to encapsulte this (potentially "globally")? I know that its possible to wrap parameters to model and use ModelState.IsValid like in this post: https://stackoverflow.com/a/39538103/766304
That is maybe one step forward on same places but generally I don't that it's realistic to wrap all parameters to models everywhere (~1 class definition per 1 action method... how nice is that?).
Also this is again per action ceremony which should be handled somewhere centralized:
if (ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
The easiest way to do it would be to create a model class and use [Required] attributes like this:
public class FooModel
{
[Required]
public string ParamA {get;set;}
[Required]
public string ParamB {get;set;}
[Required]
public string ParamC {get;set;}
}
And then use it in your controller like this:
public ActionResult DoSomething(FooModel model)
{
if (!ModelState.IsValid)
{
// return some errors based on ModelState
}
//Actual Code
}
If you are looking for more global approach, then i believe you could look into Action Filters and use OnActionExecuting filter and handle the validation there (haven't used that myself tho).
Here is how to do it:
How can I centralize modelstate validation in asp.net mvc using action filters?
That way your method would never be called if any of the parameters were missing.
The model annotations with [Required] [Length] and all these attributes is one of the most common ways to validate your model, specially it integrates with the Razor View engine and generates JavaScript validation as well, the same will happen if you are using EntityFramework for your back end, so this way you will have validation at the level of the UI, Controller and Data access.
You can also use Code Contracts which allows you to put pre and post conditions for your method in a nice way https://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx
If none of the above is still not enough, then you can add some checks in either your controller action or in your business domain service to make some business validation and return an error code if any errors found

spring-mvc swagger how to hide model property in swagger ui?

We are using SwaggerSpringMvcPlugin to generate swagger documentation as shown below.
#Bean
public SwaggerSpringMvcPlugin swaggerSpringMvcPlugin(SpringSwaggerConfig springSwaggerConfig) {
log.debug("Starting Swagger");
StopWatch watch = new StopWatch();
watch.start();
SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(springSwaggerConfig)
.apiInfo(apiInfo())
.genericModelSubstitutes(ResponseEntity.class)
.includePatterns(DEFAULT_INCLUDE_PATTERN);
swaggerSpringMvcPlugin.build();
watch.stop();
log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
return swaggerSpringMvcPlugin;
}
I need to exclude some of the model properties as shown below. I tried using #ApiModelProperty(access="hidden", hidden=true), but they are not excluded. Note that all the propeties of MyModel are displayed including status field. Any help appreciated.
public class MyModel implements Serializable {
....
#ApiModelProperty(access="hidden", hidden=true)
#Column(name = "status")
private String status;
...
}
You can simply use
public class MyModel implements Serializable {
#ApiModelProperty(hidden=true)
private String status;
}
Assuming that you dont want to show this property or allow it to be editable via serialization, I'd say just adding the
#JsonIgnore
Jackson2 annotation on your bean property will tell the model generation to excluded the property from being generated.
Also, keep in mind that, the annotation needs to be placed on the beans on getters or fields depending on how the ObjectMapper serialization/deserialization is configured.
If you merely want to hide the field from the swagger ui and allow modification/serialization of that field, then its not currently possible. However in the next version of the library, we plan to make this possible

ASP.NET MVC - Posting a form with custom fields of different data types

In my ASP.NET MVC 2 web application, I allow users to create custom input fields of different data types to extend our basic input form. While tricky, building the input form from a collection of custom fields is straight-forward enough.
However, I'm now to the point where I want to handle the posting of this form and I'm not certain what the best way to handle this would be. Normally, we'd use strongly-typed input models that get bound from the various statically-typed inputs available on the form. However, I'm at a loss for how to do this with a variable number of input fields that represent different data types.
A representative input form might look something like:
My date field: [ date time input
control ]
My text field: [ text input
field ]
My file field: [ file upload
control ]
My number field: [ numerical input control ]
My text field 2: [text input field ]
etc...
Ideas I've thought about are:
Sending everything as strings (except for the file inputs, which would need to be handled specially).
Using a model with an "object" property and attempting to bind to that (if this is even possible).
Sending a json request to my controller with the data encoded properly and attempting to parse that.
Manually processing the form collection in my controller post action - certainly an option, but I'd love to avoid this.
Has anyone tackled an issue like this before? If so, how did you solve it?
Update:
My "base" form is handled on another input area all together, so a solution doesn't need to account for any sort of inheritence magic for this. I'm just interested in handling the custom fields on this interface, not my "base" ones.
Update 2:
Thank you to ARM and smartcaveman; both of you provided good guidance for how this could be done. I will update this question with my final solution once its been implemented.
This is how I would begin to approach the issue. A custom model binder would be pretty easy to build based on the FormKey property (which could be determined by the index and/or label, depending).
public class CustomFormModel
{
public string FormId { get; set; }
public string Label { get; set; }
public CustomFieldModel[] Fields { get; set; }
}
public class CustomFieldModel
{
public DataType DateType { get; set; } // System.ComponentModel.DataAnnotations
public string FormKey { get; set; }
public string Label { get; set; }
public object Value { get; set; }
}
public class CustomFieldModel<T> : CustomFieldModel
{
public new T Value { get; set; }
}
Also, I noticed one of the comments below had a filtered model binder system. Jimmy Bogard from Automapper made a really helpful post about this method at http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx , and later revised in, http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/11/19/a-better-model-binder-addendum.aspx . It has been very helpful for me in building custom model binders.
Update
I realized that I misinterpreted the question, and that he was specifically asking how to handle posting of the form "with a variable number of input fields that represent different data types". I think the best way to do this is to use a structure similar to above but leverage the Composite Pattern. Basically, you will need to create an interface like IFormComponent and implement it for each datatype that would be represented. I wrote and commented an example interface to help explain how this would be accomplished:
public interface IFormComponent
{
// the id on the html form field. In the case of a composite Id, that doesn't have a corresponding
// field you should still use something consistent, since it will be helpful for model binding
// (For example, a CompositeDateField appearing as the third field in the form should have an id
// something like "frmId_3_date" and its child fields would be "frmId_3_date_day", "frmId_3_date_month",
// and "frmId_3_date_year".
string FieldId { get; }
// the human readable field label
string Label { get; }
// some functionality may require knowledge of the
// Parent component. For example, a DayField with a value of "30"
// would need to ask its Parent, a CompositeDateField
// for its MonthField's value in order to validate
// that the month is not "February"
IFormComponent Parent { get; }
// Gets any child components or null if the
// component is a leaf component (has no children).
IList<IFormComponent> GetChildren();
// For leaf components, this method should accept the AttemptedValue from the value provider
// during Model Binding, and create the appropriate value.
// For composites, the input should be delimited in someway, and this method should parse the
// string to create the child components.
void BindTo(string value);
// This method should parse the Children or Underlying value to the
// default used by your business models. (e.g. a CompositeDateField would
// return a DateTime. You can get type safety by creating a FormComponent<TValue>
// which would help to avoid issues in binding.
object GetValue();
// This method would render the field to the http response stream.
// This makes it easy to render the forms simply by looping through
// the array. Implementations could extend this for using an injected
// formatting
void Render(TextWriter writer);
}
I am assuming that the custom forms can be accessed via some sort of id which can be contained as a form parameter. With that assumption, the model binder and provider could look something like this.
public interface IForm : IFormComponent
{
Guid FormId { get; }
void Add(IFormComponent component);
}
public interface IFormRepository
{
IForm GetForm(Guid id);
}
public class CustomFormModelBinder : IModelBinder
{
private readonly IFormRepository _repository;
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult result;
if(bindingContext.ValueProvider.TryGetValue("_customFormId", out result))
{
var form = _repository.GetForm(new Guid(result.AttemptedValue));
var fields = form.GetChildren();
// loop through the fields and bind their values
return form;
}
throw new Exception("Form ID not found.");
}
}
Obviously, all the code here is just to get the point across, and would need to be completed and cleaned up for actual use. Also, even if completed this would only bind to an implementation of the IForm interface, not a strongly typed business object. (It wouldn't be a huge step to convert it to a dictionary and build a strongly typed proxy using the Castle DictionaryAdapter, but since your users are dynamically creating the forms on the site, there is probably no strongly typed model in your solution and this is irrelevant). Hope this helps more.
Take a peek at what I did here: MVC2 Action to handle multiple models and see if can get you on the right track.
If you use a FormCollection as one of your parameters to your action, you can then go thru that form collection looking for bits of data here or there in order to bind those values to whatever an then save the data. You are most likely going to need to take advantage of both strategy and command patterns to get this to work.
Best of luck, feel free to ask follow-up questions.
Edit:
Your method which does the work should look something like this:
private/public void SaveCustomFields(var formId, FormCollection collection) //var as I don't know what type you are using to Id the form.
{
var binders = this.binders.select(b => b.CanHandle(collection)); //I used IOC to get my list of IBinder objects
// Method 1:
binders.ForEach(b => b.Save(formId, collection)); //This is the execution implementation.
// Method 2:
var commands = binders.Select(b => b.Command(formId, collection));
commands.ForEach(c => c.Execute());
}
public DateBinder : IBinder //Example binder
{
public bool CanHandle(FormCollection collection)
{
return (null != collection["MyDateField"]); //Whatever the name of this field is.
}
//Method 1
public void Save(var formId, FormCollection collection)
{
var value = DateTime.Parse(collection["MyDateField"]);
this.someLogic.Save(formId, value); //Save the value with the formId, or however you wish to save it.
}
//Method 2
public Command Command(var formId, FormCollection collection)
{
//I haven't done command pattern before so I'm not sure exactly what to do here.
//Sorry that I can't help further than that.
}
}
I would think one of the best options is to create a custom model binder, which makes it possible to have custom logic behind the scenes and still very customizable code behind.
Maybe these articles can help you:
http://www.gregshackles.com/2010/03/templated-helpers-and-custom-model-binders-in-asp-net-mvc-2/
http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC.aspx
More specifically I would probably take as the controller argument a custom class with all "base" properties included. The class could then for example include a dictionary linking the name of each field to either just an object or an interface which you implement once for each data-type making it simple to process the data later.
/Victor

Bypass Data Annotations validation on ASP.NET MVC 2

I would like to know if it's possible to bypass the validation of one property which is using Data Annotations. Since I use the model across multiple pages, there's a check I need in some, but not in others, so I would like it to be ignored.
Thaks!
You could use FluentValidation, which uses as external validator class. In this case you would implement a different validator class for each scenario.
http://fluentvalidation.codeplex.com/
Example:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty()
.WithMessage("Please specify a first name");
}
}
public class CustomerValidator2: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
CustomerValidator2 validator2 = new CustomerValidator2();
ValidationResult results2 = validator2.Validate(customer);
results would have 2 validation errors
results2 would have 1 validation error for the same customer
I don't believe this is possible with Data Annotations. I know the Microsoft Enterprise Library Validation Application Block has the notion of rule sets to group validations. This allows you to validate an object on several rule sets, for instance the default ruleset and on some pages the extended rule set. Data Annotations does not have something like rule sets.
Here is an example using VAB:
public class Subscriber
{
[NotNullValidator]
[StringLengthValidator(1,200)]
public string Name { get; set; }
[NotNullValidator(Ruleset="Persistence")]
[EmailAddressValidator]
public string EmailAddress { get; set; }
}

Resources