How we can get the invalid value that we have pass in the request from Set<ConstraintViolation<Object>> - java

Currently, I am validating my request using javax validation.
Set<ConstraintViolation<Request>> constraintViolations = validator
.validate(Request);
So from constraint violations I want two things,
constraint violation.getPropertyPath() which will return which fields is violating
I want the invalid value that I was passing in the request for the fields from the constraintViolations variable
So how we can get the invalid value?
For 2. I tried using constraintViolation.getInvalidValue() this but it is giving like com.practice.domain.PaymentInstrumentRequest#258d8cb5
I want specific value that I have passed in that field.

Related

SpringBoot: requestParam value validation when required=false

Here is my method code:
#RequestMapping(value="/api/restcall", method=GET)
public response methodcall (#RequestParam (value="testId", required=false) String testId, #RequestParam (value="requestId", required=false) String requestId){
//some code
}
I want to validate the request params. Not the value but the field itself.
API call:
localhost:8080/api/restcall?requestId=abcd&testId=xyz
I want to validate that "requestId" and "testId" are sent correctly if sent. Not the value, but the key itself. NOTE: The requestParams are not mandatory fields.
So if below API call is made:
localhost:8080/api/restcall?request=abcd&test=xyz
I want the code to validate that the requestparams are not correct. I tried the #Validate annotation and #Valid annotation. Both did not work.
When incorrect call is made like above, the code is going through as the fields are not mandatory.
I want to know what params are coming in if testId and requestId are not sent in. If I have this information, I can do the validation.
The validation of REST invocations doesn't work in this way.
This validates the values of the sent parameters, not the names of them.
So as the required attribute is set to false for the parameters, no violation constraint occurs.
The invalid names of the sent parameters are probably ignored by the Jackson processing.
If you want to perform such a validation, you should use a custom validator or a custom validation.
For example :
String errorMsg = "";
if (StringsUtil.isEmpty(testId)){
errorMsg+="testId param name missing";
}
if (StringsUtil.isEmpty(requestId)){
errorMsg+="requestId param name missing";
}
if (!errorMsg.equals("")){
throw new ValidationException(errorMsg);
}
You can get a map with all params fields and values with: #RequestParam Map<String,String> allRequestParams. Then you can use containsKey to check for a field.

Returning error from GrapQL-Java

I would like to validate input provided by user during mutation and then provide errors if there are some invalid fields provided.
There is a question which answers the question for GraphQL-JS here
I want to ask this question about implementation using GraphQL-Java.
Let's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.
{errors: {field1: "is required"}}
How do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?
The graphql-java implementation has a class for checking if the query is not valid (i.e. graphql.validation.Validatior). That way you can validate your query string before executing them.
If the query is invalid you can create a method that takes List<ValidationError> as a parameter that generate the error response.
Example:
List<ValidationError> errors = validator.validateDocument(graphQLSchema, requestString);
if (!errors.isEmpty()) { return executeError(errors); }

Type mismatch, Spring BindException

When I input alphabets such as "adsf" in the input field, spring tries to bind it to my price( a double) property of my "Code" object and this causes the bind exception. What can I do to avoid this error, if I wanted to keep the field as a double?
POJO
#entity
#Table(name=“CODE”)
public class Code{
#Column(name=“PRICE”)
#NotNull
#DecimalMax(value=“999999999999.999999”)
#DemimalMin(value=“0.0”)
private Double price;
//getters and setters
}
My controller
#RequestMapping(value=“validateField”, method=RequestMethod.POST, produces=“application/json”)
public FieldValidatinResult validateField(final Code code, final String field){
//return statement
}
html page
<input type=“text” class=“form-control validatable” id=“price”></input>
Error message:
Field error in object ‘code’ on field ‘price’: rejected value [adsf];
codes[typeMismatch.code.price,typeMismatch.price,typeMismatch.java.lang.Double,typeMismatch]; arguments[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [code.price,price]; arguments []; default message [price]]; default message
[Failed to convert property value of type 'java.lang.String' to required type
'java.lang.Double' for property 'price'; nested exception is
java.lang.NumberFormatException: For input string: "adsf"]
I would not say that validations on client side are 'best' as they can be easily avoided ( take action url from form, post some garbage ), but its probably the easiest to do.
I would recommend to add validation also on server side. You have your annotations ready, now you have to use #Valid on your Code code and BindingResult parameter. http://codetutr.com/2013/05/28/spring-mvc-form-validation/ <- this seems to be some useful tutorial.
Error clearly says
[Failed to convert property value of type 'java.lang.String' to required type
'java.lang.Double' for property 'price'; nested exception is
java.lang.NumberFormatException: For input string: "adsf"]
User has provided a non number input and when it is parsed as double on server it is throwing NumberFormatException. Best way to solve this is to handle it client side. Add a validation like below before submitting the form
if (!isNaN(parseInt($("#price").val()))) {
//proceed with form submit
}

JSR 303 / ConstraintValidatorContext: Parameterized Error Messages

if I have a ConstraintValidatorContext and I'm constructing a ConstraintViolationContextBuilder using buildConstraintViolationWithTemplate(String messageTemplate), is there any possibility to pass custom parameter values?
The corresponding properties file would look somehow like this:
Foobar.invalidValue.message=Invalid value. Valid values are {VALID_VALUES}
I then would like to programmatically set the value for {VALID_VALUES}.
Do you have any ideas?
You can only refer to attributes of the concerned constraint annotation within message templates, e.g. like so for a constraint with attributes min and max:
size must be between {min} and {max}
So you could specify your valid values as annotation attribute.
If you're using Hibernate Validator as Bean Validation provider, you might implement a custom ResourceBundleLocator which returns bundles with keys for your values:
public class MyResourceBundleLocator implements ResourceBundleLocator {
public ResourceBundle getResourceBundle(Locale locale) {
//return a bundle with keys for your values, e.g. set dynamically
}
}
Then set the locator when obtaining a validator:
Validator validator Validation.byProvider(HibernateValidator.class)
.configure()
.messageInterpolator(
new ResourceBundleMessageInterpolator(
new MyResourceBundleLocator() ) )
.buildValidatorFactory()
.getValidator();
Alternatively you could just format and prepare the message yourself and pass it to buildConstraintViolationWithTemplate().
I found a solution that allows customized Constraint annotations with parameterized error messages: see this question for more details: Parameterized error messages for javax.validation.constraints.Pattern annotation?

Spring "typemismatch" and required fields

In the context of Spring Webflow 2.0.x......
I handle form binding "typemismatches", i.e. as a result of trying to map a String onto a Integer field, by using the following in my messages.properties
typeMismatch={0} contains invalid data.
This works fine.
The problem is that if the field that the typeMismatch error occurred on was "required" then I also receive an error for the missing required field, which is logical I guess because the value that was submitted was never bound. ("Required" being defined in a Commons Validation XML file)
So, I dont want to see the "XXX is required field" error message when the field is only missing due to the typeMismatch. How do I resolve this? I thought about overriding initBinder() on the FormAction but quickly got nowhere.....
Like Yves mentioned, among the three approaches, i have used a custom validator method and its very easy. You can use a custom validator which checks if the form field already has a xml error message of required. If the field does not have an error, then you can check for your string validation. That way it will display only one.
The other method that you could use is try a multiple xml validation, one being required and the other one being a mask which checks for a particular regular expression. In your case if your field is an integer field, then you can go and perform a mask with regex checking for only numbers. The order of mask, required or required, mask in the xml decides which message gets a higher preference.
For example:
<field property="somefield" depends="required,mask" page="2">
<arg key="somelabel"/>
<var>
<var-name>mask</var-name>
<var-value>${somepattern}</var-value>
</var>
</field>
You have many options, in order of preference:
Set selectively the message typeMismatch.target.yourFieldName or typeMismatch.int in resources files
Implement your own Validator so that you can send a dedicated message when Integer parsing will fail before the binding step
Create a BindingErrorProcessor to handle different kind of parsing issues

Categories

Resources