When I annotate a field with #Pattern
#Pattern(regexp="someRegexp")
public String name;
If the JSON contains this field, with value as null, then I expect this regex to fail and thus invalid.
if the JSON does NOT contain this field, then it is fine for the validation to pass.
How to achieve this?
To Strings, I usually use #NotBlank for not empty strings, but im not sure at 100% that it doesnt allow null entries, but, in this case, use #NotNull annotation.
Edit: I was looking for an example and I got this from an old project:
#NotNull
#NotBlank
#Pattern(regexp = "somePattern")
public String getEmail() {
return this.email;
}
As you can see, I use NotNull and NotBlank even though I have a pattern there.
Related
I am developing a service using Dropwizard. In a POST request I receive a JSON and I want to throw an exception if the format of the request is not valid, in particular if some fields are missing. By default, as in the documentation, the Hibernate Validator is being used. This is the code:
public class ExtranetRequest {
#NotEmpty(message = "extranet_request_id should not be empty")
public String extranet_request_id;
#NotNull
public int hotel_id;
public List<ShopPattern> shop_patterns;
}
Everything works as expected for the field extranet_request_id (an exception is thrown if the field is not present in the JSON). However the request no error is raised if the field hotel_id is missing. I also tried the annotations #NotEmpty, #NotBlank, #Min(0), but none of them worked.
Did you try to make the hotel_id field an Integer?
An int cannot be null so it will be 0 by default which is OK for #NotNull or #Min(0) (it's checking that the number is higher or equal).
#NotEmpty or #NotBlank should make Hibernate Validator throw an exception though.
Is there a validation annotation for Spring that will do something like:
#ValidString({"US", "GB", "CA"})
final String country;
and validate that the string is one of the supported values in the array?
You need to create a custom annotation to do this, I would say have an annotation which accepts enum over string comparison, and use it something like this.
public enum CountryCode {
US,
GB,
CA;
}
#ValidateString(CountryCode.STRING)
String code;
You may go thru all the responses in this question
Java String validation using enum values and annotation
A not so clean way is to use #Pattern annotation with all the country codes in regex.
#Pattern(regexp="^(AF|AX|AL|DZ|AS|AD|AO|AI|AQ|AG|AR|AM|AW|AU|AT|AZ|BS|BH|BD|BB|BY|BE|BZ|BJ|BM|BT|BO|BQ|BA|BW|BV|BR|IO|BN|BG|BF|BI|KH|CM|CA|CV|KY|CF|TD|CL|CN|CX|CC|CO|KM|CG|CD|CK|CR|CI|HR|CU|CW|CY|CZ|DK|DJ|DM|DO|EC|EG|SV|GQ|ER|EE|ET|FK|FO|FJ|FI|FR|GF|PF|TF|GA|GM|GE|DE|GH|GI|GR|GL|GD|GP|GU|GT|GG|GN|GW|GY|HT|HM|VA|HN|HK|HU|IS|IN|ID|IR|IQ|IE|IM|IL|IT|JM|JP|JE|JO|KZ|KE|KI|KP|KR|KW|KG|LA|LV|LB|LS|LR|LY|LI|LT|LU|MO|MK|MG|MW|MY|MV|ML|MT|MH|MQ|MR|MU|YT|MX|FM|MD|MC|MN|ME|MS|MA|MZ|MM|NA|NR|NP|NL|NC|NZ|NI|NE|NG|NU|NF|MP|NO|OM|PK|PW|PS|PA|PG|PY|PE|PH|PN|PL|PT|PR|QA|RE|RO|RU|RW|BL|SH|KN|LC|MF|PM|VC|WS|SM|ST|SA|SN|RS|SC|SL|SG|SX|SK|SI|SB|SO|ZA|GS|SS|ES|LK|SD|SR|SJ|SZ|SE|CH|SY|TW|TJ|TZ|TH|TL|TG|TK|TO|TT|TN|TR|TM|TC|TV|UG|UA|AE|GB|US|UM|UY|UZ|VU|VE|VN|VG|VI|WF|EH|YE|ZM|ZW)$",message="invalid code")
private String countryCode;
We have a requirement that every fields of the object must be validated in a special order.
For example, we have Person object like below:
public class Person {
#NotNull
private String firstName;
#NotNull
private String lastName;
// getter and setter
}
When I use the javax.validation.Validator to validate this object, we need to make sure that the firstName always be validated first and then lastName. Is there any way for hibernate validator archive that requirement?
You want to use group sequences. In particular you probably want to redefine the default group for your entity. See also Redefining the Default group for a class as defined by the Bean Validation specification .
I currently galley with data validation via Hibernate. Especially with the #Pattern annotation
Wholesale verification is always false, no matter what I do, so I can not save the object.
I try this, among other things:
#NotNull
#Size(max=30)
#SafeHtml
#Pattern(regexp="[a-zA-Z]", messsage="the name can only contain letters")
private String name;
et ceci :
#NotNull
#Size(max=30)
#SafeHtml
#Pattern(regexp="\\D", messsage="the name can only contain letters")
private String name;
In both case, if i write "toto," I have the error message that appears.
Someone an idea?
Have you tried [a-zA-Z]*
The patterns you have look like they only capture one letter. You need a * or a + to suggest multiple letters.
I have a simple JSF+RichFaces form with some fields and obviously a backing bean to store them. In that bean all the necessary properties have validation annotations (jsr303/hibernate), but I can't seem to find an annotation which would check if the property (String) is blank. I know there's a #NotBlank annotation in spring modules, but JSF doesn't support spring validation. Is there any easy way to check it or should I write my own annotation?
#Edit: I already tried #NotNull and #NotEmpty from jsr303 and hibernate, but they both failed I still can send a blank string like " ".
If you use Hibernate Validator 4.1 as your JSR-303 implementation, they provide a #NotBlank annotation that does EXACTLY what you're looking for, separate from #NotNull and #NotEmpty. You need to be using the (currently) latest version, but that will work.
If you can't go to the latest version for some reason, it doesn't take much to write an annotation yourself.
Hibernate Validator 4.1+ provides a custom string-only #NotBlank annotation that checks for not null and not empty after trimming the whitespace. The api doc for #NotBlank states:
The difference to NotEmpty is that trailing whitespaces are getting ignored.
If this isn't clear that #NotEmpty is trimming the String before the check, first see the description given in the 4.1 document under the table 'built-in constaints':
Check that the annotated string is not null and the trimmed length is greater than 0. The difference to #NotEmpty is that this constraint can only be applied on strings and that trailing whitespaces are ignored.
Then, browse the code and you'll see that #NotBlank is defined as:
#Documented
#Constraint(validatedBy=NotBlankValidator.class)
#Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
#Retention(value=RUNTIME)
#NotNull
public #interface NotBlank{
/* ommited */
}
There are two things to note in this definition. The first is that the definition of #NotBlank includes #NotNull, so it's an extension of #NotNull. The second is that it extends #NotNull by using an #Constraint with NotBlankValidator.class. This class has an isValid method which is:
public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {
if ( charSequence == null ) { //this is curious
return true;
}
return charSequence.toString().trim().length() > 0; //dat trim
}
Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It's ok that it returns true if it's null because, as I mentioned, the #NotEmpty definition also requires #NotNull.
Perhaps #NotEmpty ?
Which is defined as:
#NotNull
#Size(min=1)
Since you are using richfaces, I guess you are using <rich:beanValidator />? It handles JSR 303 annotations.
Update: Try (taken from here):
#Pattern(regex="(?!^[\s]*$)").