LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 10

Form validators combined with default methods in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Write a functional Validator<T> interface returning an error message or null, with default and(other) and static helpers notBlank, maxLength and matches; validate several sign-up form values.

Solution
Main.java
@FunctionalInterface
interface Validator<T> {
    String check(T value);                       // null = valid

    default Validator<T> and(Validator<T> other) {
        return v -> { String e = check(v); return e != null ? e : other.check(v); };
    }

    static Validator<String> notBlank(String field) { return s -> s == null || s.isBlank() ? field + " is required" : null; }
    static Validator<String> maxLength(String field, int n) { return s -> s.length() > n ? field + " max " + n + " chars" : null; }
    static Validator<String> matches(String field, String regex) { return s -> s.matches(regex) ? null : field + " is invalid"; }
}

public class Main {
    public static void main(String[] args) {
        Validator<String> username = Validator.notBlank("username").and(Validator.maxLength("username", 12)).and(Validator.matches("username", "[a-z0-9_]+"));
        Validator<String> mobile = Validator.notBlank("mobile").and(Validator.matches("mobile", "[6-9]\\d{9}"));
        Validator<Integer> age = a -> a < 18 ? "must be 18+" : null;

        for (String u : new String[]{"asha_21", " ", "Asha!", "averyveryverylongname"}) {
            String e = username.check(u);
            System.out.println("[" + u + "] " + (e == null ? "ok" : e));
        }
        System.out.println(mobile.check("9876543210") + " | " + mobile.check("12345") + " | " + age.check(16) + " | " + age.check(30));
    }
}

Output Verified by compiling and running

[asha_21] ok
[ ] username is required
[Asha!] username is invalid
[averyveryverylongname] username max 12 chars
null | mobile is invalid | must be 18+ | null

A generic functional interface with default and static methods lets small rules be combined into readable validators; the first failure wins.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links