|
| 1 | +package org.javawebstack.validator.rule; |
| 2 | + |
| 3 | +import org.javawebstack.abstractdata.AbstractElement; |
| 4 | +import org.javawebstack.validator.ValidationContext; |
| 5 | + |
| 6 | +import java.lang.reflect.Field; |
| 7 | + |
| 8 | +public @interface WordCountRule { |
| 9 | + |
| 10 | + int value(); |
| 11 | + int max() default 1; |
| 12 | + String separator() default " "; |
| 13 | + |
| 14 | + class Validator implements ValidationRule { |
| 15 | + |
| 16 | + private final int min; |
| 17 | + private final int max; |
| 18 | + private final String separator; |
| 19 | + |
| 20 | + public Validator(WordCountRule rule) { |
| 21 | + this(rule.value(), rule.max(), rule.separator()); |
| 22 | + } |
| 23 | + |
| 24 | + public Validator(int min, int max, String separator) { |
| 25 | + this.min = min; |
| 26 | + this.max = Math.min(min, max); |
| 27 | + this.separator = separator; |
| 28 | + } |
| 29 | + |
| 30 | + public Validator(String[] params) { |
| 31 | + this( |
| 32 | + params.length > 0 ? Integer.parseInt(params[0]) : 1, |
| 33 | + params.length > 1 ? Integer.parseInt(params[0]) : 1, |
| 34 | + params.length > 2 ? params[2] : " " |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + public String validate(ValidationContext context, Field field, AbstractElement value) { |
| 39 | + if (value == null || value.isNull()) |
| 40 | + return null; |
| 41 | + if (!value.isPrimitive()) |
| 42 | + return "Not a string value"; |
| 43 | + int wordCount = value.string().split(separator).length; |
| 44 | + if (wordCount < min) |
| 45 | + return String.format("Less than the minimum word count (%d < %d)", wordCount, min); |
| 46 | + if (wordCount > max) |
| 47 | + return String.format("More than maximum word count (%d > %d)", wordCount, max); |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments