I'm looking for a possiblity to validate IP addresses in my Spring roo project.
My entity looks like this
package com.ip.test.domain;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class IP {
@NotNull
@Size(min = 7, max = 15)
private String ip;
@ManyToOne
private Hoster Hoster;
}
With this setup it validates only if the string contains 7 to 15 characters, but not really if it's an IP address.
Something like
@validIpAddress
private String ip;
would be nice.
Any idea if that's possible?
You can use the JSR 303 Pattern validator, with an IP address regex:
@NotNull
@Pattern(regexp = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")
private String ip;
edit: escape backslash
Definitely possible. You will need to code a custom annotation and implementation class. Not too much effort. See here for background: http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#validator-customconstraints
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Documented
@Constraint(validatedBy = IpAddressValidator.class)
public @interface IpAddress
{
String message() default "{ipAddress.invalid}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and
public class IpAddressValidator implements ConstraintValidator<IpAddress, Object>
{
@Override
public void initialize(IpAddress constraintAnnotation)
{
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext cvContext)
{
// logic here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With