Wiki

Clone wiki

specter / validators

Validators

The procedure to define a validator is quite similar to the one explained with converters but with the difference that, instead of performing at a class level for all attributes with the same type, the validators can be asociated to more than one attribute within the class, meaning that we have the hability to define different behaviours for the same validation rule.

So, the first step to define a validator would be the creation of the annotations that we're going to use to let the framework know of the need of validating an attribute with the associated rule. For that, we can start by creating an annotation as follows:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateUser {

}

As long as we have the required annotation, the next step would be the definition by the rule itself, where we have to define what this validation process constists of. Therefore, we have to create a class that implements the interface edu.uoc.pfc.specter.core.validator.DataValidator, which will ask you to specify what type it's going to be validated. A good example for a validator could be as follows:

@ValidationRule(associatedTo=ValidateUser.class)
public class UserValidationRule implements DataValidator<User>{

	private List<ErrorMessage> _lstErrors = new ArrayList<ErrorMessage>();
	
	@Override
	public boolean validate(Annotation p_oSourceAnnotation, User p_oSource)
			throws SpecterValidationException {

		boolean blResult = true;
		
		if(p_oSource.getName() == null || p_oSource.getName().trim().length() <= 0)
		{
			_lstErrors.add(new ErrorMessage("name","user.name.empty"));
			
			blResult = false;
		}

		if(p_oSource.getLastname() == null || p_oSource.getLastname().trim().length() <= 0)
		{
			_lstErrors.add(new ErrorMessage("lastname","user.lastname.empty"));
			
			blResult = false;
		}		
		
		return blResult;
	}

	@Override
	public List<ErrorMessage> getErrors() {

		return _lstErrors;
	}

}

As you can see, in order for the framework to find and register our validation rule, we need to annotate our new class with the annotation @ValidationRule along with the attribute associatedTo which will contain the class of the annotation that we're going to use to reference the actual validation rule within the code, and in our example, this class is ValidateUser

Updated