Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring IP address validation

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?

like image 902
mbs Avatar asked Feb 14 '13 14:02

mbs


2 Answers

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

like image 162
David Rabinowitz Avatar answered Oct 06 '22 23:10

David Rabinowitz


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
  }
}
like image 26
sbk Avatar answered Oct 06 '22 21:10

sbk