Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/main/java/org/javawebstack/validator/rule/RequiredRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,28 @@
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredRule {
boolean allowEmptyStrings() default false;

class Validator implements ValidationRule {
public Validator(RequiredRule rule) {} // needed
private final boolean allowEmptyStrings;
public Validator(RequiredRule rule) {
this.allowEmptyStrings = rule.allowEmptyStrings();
}

public Validator() {}
public Validator(boolean allowEmptyStrings) {
this.allowEmptyStrings = allowEmptyStrings;
}

public Validator() {
this.allowEmptyStrings = false;
}

public String validate(ValidationContext context, Field field, AbstractElement value) {
return !value.isNull() ? null : "Missing required field";
if (value.isNull())
return "Missing required field";
if (value.getType() == AbstractElement.Type.STRING && !allowEmptyStrings && value.string().length() == 0)
return "Missing required field";
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.javawebstack.validator.Rule;
import org.javawebstack.validator.ValidationContext;
import org.javawebstack.validator.Validator;
import org.javawebstack.validator.rule.RequiredRule;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
Expand All @@ -21,6 +22,17 @@ public void testSimpleRequiredRule() {
assertTrue(validator.validate(new ValidationContext(), new AbstractMapper().toAbstract(test)).isValid());
}

@Test
public void testEmptyStringOption() {
Validator validator = Validator.getValidator(TestObject1.class);
TestObject1 test = new TestObject1();
test.name = "";
assertFalse(validator.validate(new ValidationContext(), new AbstractMapper().toAbstract(test)).isValid());
test.name = "Test";
test.password = "";
assertTrue(validator.validate(new ValidationContext(), new AbstractMapper().toAbstract(test)).isValid());
}

@Test
public void testInnerRequiredRule() {
Validator validator = Validator.getValidator(TestObject2.class);
Expand All @@ -36,10 +48,11 @@ public void testInnerRequiredRule() {
assertTrue(validator.validate(new ValidationContext(), new AbstractMapper().toAbstract(test)).isValid());
}


private static class TestObject1 {
@Rule("required")
String name;
@Rule("req")
@RequiredRule(allowEmptyStrings = true)
String password;
}

Expand Down