The Validator library makes it easy to validate multiple form fields with different validation rules. This guide demonstrates how to create a complete registration form with proper validation handling.
First, create a central place to define your validators:
Validators.java
import io.github.ApamateSoft.validator.Validator;import static io.github.ApamateSoft.validator.utils.Alphabets.*;public class Validators { public static final Validator email = new Validator.Builder() .required() .email() .build(); public static final Validator phone = new Validator.Builder() .required() .numberPattern("(xxxx) xx-xx-xxx") .build(); public static final Validator password = new Validator.Builder() .required() .minLength(12) .mustContainMin(3, ALPHA_LOWERCASE) .mustContainMin(3, ALPHA_UPPERCASE) .mustContainMin(3, NUMBER) .mustContainMin(3, "@~_/") .build();}
import io.github.ApamateSoft.validator.Validator;import io.github.ApamateSoft.validator.exceptions.InvalidEvaluationException;public class Register { private RegisterPojo register = new RegisterPojo("", "", "", ""); public void submit() { try { Validator.validOrFail(register); // TODO proceed with submit } catch (InvalidEvaluationException e) { switch (e.getKey()) { case "email": // TODO: handle error for email break; case "psw": // TODO: handle error for password break; case "phone": // TODO: handle error for phone break; } } }}
Annotations only work with String fields. The Validator.validOrFail(Object) method inspects the object’s String fields and applies the validation rules defined by the annotations.