Menu

Creating Custom Validators

Paul Russell

Custom Validators

I've tried to make the creation of new Validators as simple as possible. To create a custom validation component, simply implement the ValidationElement interface:

    public class EmailValidator implements ValidationElement {

        private final String emailField;

        public EmailValidator(String emailField) {
            this.emailField = emailField;
        }

        @Override 
        //you will have to override this method.
        //and possibly add a new return type to the ValidationResultType enum
        public ValidationResultType isValid(String fieldContents) {
            if (isValidEmail(fieldContents)) {
                return ValidationResultType.VALID;
            }
            return ValidationResultType.INVALID_EMAIL;
        }

        private boolean isValidEmail(String emailField) {
            //I have used well-known REGEXs, but please use your own as required
            Matcher matcher = ValidationRegex.VALID_EMAIL_ADDRESS_REGEX.matcher(emailField);
            return matcher.find();
        }
    }

As you can see, an enum ValidationResultType is returned by Validators. To enable the creation of new tooltip messages, add these to the ValidationResultType class, in the validationElements package.

    public enum ValidationResultType {
        VALID, FIELD_TOO_LONG, FIELD_DONT_MATCH, INVALID_EMAIL, FIELD_TOO_SHORT, MY_VALIDATION_TYPE
    }

This program uses widely available REGEXs, as available on sites like http://www.regular-expressions.info/ and others. You would be advised to test out those I have used, and, where necessary replace/overwrite those inside the validationElements->ValidationRegex class.


Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.