Skip to content

Commit bb1a136

Browse files
committed
Implemented a WordCountRule
1 parent c106445 commit bb1a136

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/main/java/org/javawebstack/validator/Validator.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ public class Validator {
4646
registerRuleType("regex", RegexRule.Validator.class, RegexRule.class);
4747
registerRuleType("uuid", UUIDRule.Validator.class, UUIDRule.class);
4848
registerRuleType("charset", CharsetRule.Validator.class, CharsetRule.class);
49+
registerRuleType("word_count", WordCountRule.Validator.class, WordCountRule.class);
4950
}
5051

5152
private final Map<String[], ValidationConfig> rules = new HashMap<>();
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

Comments
 (0)