Skip to content

Commit d9824ef

Browse files
committed
replace validate method with tryValidate
1 parent f4d549a commit d9824ef

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
<groupId>dev.ditsche</groupId>
88
<artifactId>validator</artifactId>
9-
<version>1.0.3</version>
9+
<version>1.1.0</version>
1010

1111
<packaging>jar</packaging>
1212

src/main/java/dev/ditsche/validator/Validator.java

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,12 @@ public Validator<T> addField(String field, String rulesString) {
100100

101101
/**
102102
* Validates an object against a schema and returns an error bag.
103-
*
103+
* @deprecated since 1.0.4
104104
* @param object The object that need to be validated.
105105
* @throws ValidationException Thrown when at least one rule fails.
106106
* @throws IllegalAccessException Thrown when the field is not public.
107107
*/
108+
@Deprecated
108109
public void validate(T object) throws ValidationException, IllegalAccessException {
109110
errorBag.clear();
110111
List<Field> fieldSet = new ArrayList<>();
@@ -125,6 +126,33 @@ public void validate(T object) throws ValidationException, IllegalAccessExceptio
125126
throw new ValidationException(errorBag);
126127
}
127128

129+
/**
130+
* Validates an object against a schema and returns an error bag.
131+
*
132+
* @param object The object that need to be validated.
133+
* @throws ValidationException Thrown when at least one rule fails.
134+
* @throws IllegalAccessException Thrown when the field is not public.
135+
*/
136+
public void tryValidate(T object) throws ValidationException, IllegalAccessException {
137+
errorBag.clear();
138+
List<Field> fieldSet = new ArrayList<>();
139+
for (Class<?> c = object.getClass(); c != null; c = c.getSuperclass())
140+
{
141+
Field[] fields = c.getDeclaredFields();
142+
fieldSet.addAll(Arrays.asList(fields));
143+
}
144+
for(ValidationField vf : this.fields) {
145+
Field field = fieldSet.stream().filter(f -> f.getName().equals(vf.getField())).findFirst().orElse(null);
146+
if(field == null) continue;
147+
Object value = getValue(field, object);
148+
for(Rule rule : vf.getRules()) {
149+
if(!rule.passes(value)) errorBag.add(vf.getField(), rule.message(vf.getField()));
150+
}
151+
}
152+
if(!errorBag.isEmpty())
153+
throw new ValidationException(errorBag);
154+
}
155+
128156
/**
129157
* Uses reflection to invoke a getter of the validation target.
130158
* Falls back to the fields default getter. Will fail if the variable

0 commit comments

Comments
 (0)