com.vaadin.data.validator.AbstractValidator Maven / Gradle / Ivy
/*
* Copyright (C) 2000-2024 Vaadin Ltd
*
* This program is available under Vaadin Commercial License and Service Terms.
*
* See for the full
* license.
*/
package com.vaadin.data.validator;
import java.util.Objects;
import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.server.SerializableFunction;
/**
* An abstract base class for typed validators.
*
* @param
* The value type
* @author Vaadin Ltd.
* @since 8.0
*/
public abstract class AbstractValidator implements Validator {
private final SerializableFunction messageProvider;
/**
* Constructs a validator with the given error message. The substring "{0}"
* is replaced by the value that failed validation.
*
* @param errorMessage
* the message to be included in a failed result, not null
*/
protected AbstractValidator(String errorMessage) {
Objects.requireNonNull(errorMessage, "error message cannot be null");
this.messageProvider = value -> errorMessage.replace("{0}",
String.valueOf(value));
}
/**
* Returns the error message for the given value.
*
* @param value
* an invalid value
* @return the formatted error message
*/
protected String getMessage(T value) {
return messageProvider.apply(value);
}
/**
* A helper method for creating a {@code Result} from a value and a validity
* flag. If the flag is true, returns {@code Result.ok}, otherwise yields
* {@code Result.error} bearing the error message returned by
* {@link #getMessage(Object)}.
*
* For instance, the following {@code apply} method only accepts even
* numbers:
*
*
* @Override
* public Result<T> apply(Integer value) {
* return toResult(value, value % 2 == 0);
* }
*
*
* @param value
* the validated value
* @param isValid
* whether the value is valid or not
* @return the validation result
*/
protected ValidationResult toResult(T value, boolean isValid) {
return isValid ? ValidationResult.ok()
: ValidationResult.error(getMessage(value));
}
}