walled.api.interfaces.ValueValidation Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of walleed Show documentation
Show all versions of walleed Show documentation
The Simplest and Easiest Java Validation Library
The newest version!
package walled.api.interfaces;
import java.text.MessageFormat;
import java.util.Optional;
import java.util.function.Predicate;
public class ValueValidation {
private Optional target;
private String message;
private ValueValidation(Value value, Predicate predicate, String message) {
this.target = Optional.ofNullable(value).filter(predicate);
this.message = message;
}
public static ValueValidation of(T value, Predicate predicate) {
return new ValueValidation<>(value, predicate, "");
}
public static ValueValidation notEmpty(String value) {
return new ValueValidation<>(value, notEmpty(), "Value cannot be empty.");
}
public static ValueValidation notZero(Number value) {
return new ValueValidation<>(value, notZero(), "Value cannot be zero.");
}
public static ValueValidation notNull(T value) {
return new ValueValidation<>(value, notNull(), "Value cannot be null.");
}
static Predicate notZero() {
return ((value) -> value != null && value.intValue() != 0);
}
static Predicate notEmpty() {
return ((value) -> value != null && !value.isEmpty());
}
static Predicate notNull() {
return ((value) -> value != null);
}
public ValueValidation withMessage(String messsage, Object... args) {
String validationMessage = MessageFormat.format(message, args);
this.message = validationMessage;
return this;
}
public Value get() {
return this.target.orElseThrow(() -> new IllegalStateException(this.message));
}
}