2

Here is my code for creating a custom Annotation for validating Name
ValidName.java

package custom.Annotation;
import java.lang.annotation.*;
import net.sf.oval.configuration.annotation.Constraint;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.LOCAL_VARIABLE)
@Constraint(checkWith=NameValidator.class)
public @interface ValidName {
String  message() default NameValidator.message;
}

here is my code for Constraint Class

package custom.Annotation;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;
import play.Logger;
import java.util.regex.Pattern;
public class NameValidator extends AbstractAnnotationCheck<ValidName>
{    
public final static String message="custom.message";
private static final String letter = "[a-zA-Z]";
public static final Pattern VALID_PATTERN = Pattern.compile(letter);

public static boolean isValidText(String userName) {
    return VALID_PATTERN.matcher(userName).matches();
}


@Override
public void configure(ValidName annotation) {
    setMessage(annotation.message());
}
@Override
public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context,
                           Validator validator) throws OValException {
    try
    {
        if (valueToValidate == null) {
            return false;
        }
    }catch (Exception e){
        e.getMessage();
    }
           return` isValidText(valueToValidate.toString()`); 
}
}

When I applied @ValidName to any local variable nothing happened and I also am unable to debug the program. Any suggestions?

Tijkijiki
  • 792
  • 7
  • 19
adg
  • 99
  • 6
  • Why not implement custom Play Validator? [Here](http://stackoverflow.com/questions/8115106/how-to-create-a-custom-validator-in-play-framework-2-0/8115115#8115115) is nice answer to get start with. – Tijkijiki Apr 19 '16 at 21:51
  • Sorry for not mentioning I m using play 1.4.1 so play.data.validation.Constraints class is not available here – adg Apr 20 '16 at 10:33
  • @adg Play 1.x has custom validation also. https://www.playframework.com/documentation/1.4.x/validation#custom – James Jul 29 '16 at 07:24

1 Answers1

1

You need to use the oval validation by calling validate method of oval validation library.

@Autowired
@Qualifier("ovalValidator")
private Validator ovalValidator;            

List<ConstraintViolation> violations = null;
violations = ovalValidator.validate(objectToValidate);
Himanshu Sharma
  • 101
  • 1
  • 4