Skip to content

Commit 0a72cfe

Browse files
committed
Created rules for validating credit cards and ip addresses
1 parent fb6fd53 commit 0a72cfe

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package dev.ditsche.validator.rule.ruleset;
2+
3+
import dev.ditsche.validator.rule.Rule;
4+
import dev.ditsche.validator.rule.RuleResult;
5+
6+
import java.util.regex.Pattern;
7+
8+
/**
9+
* Checks if the provided value is a valid credit card number.
10+
*
11+
* @author Tobias Dittmann
12+
*/
13+
public class CreditCardRule implements Rule {
14+
15+
private final String PATTERN = "^(\\\\d{4}[- ]?){3}\\\\d{4}$";
16+
17+
@Override
18+
public RuleResult passes(Object value) {
19+
20+
if(!(value instanceof String))
21+
return RuleResult.reject();
22+
23+
return RuleResult.passes(Pattern.matches(PATTERN, String.valueOf(value)));
24+
}
25+
26+
@Override
27+
public String message(String field) {
28+
return String.format("The field \"%s\" needs to be a valid credit card", field);
29+
}
30+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package dev.ditsche.validator.rule.ruleset;
2+
3+
import dev.ditsche.validator.rule.Rule;
4+
import dev.ditsche.validator.rule.RuleResult;
5+
6+
import java.util.regex.Pattern;
7+
8+
/**
9+
* Checks for a valid ip address.
10+
*
11+
* @author Tobias Dittmann
12+
*/
13+
public class IpAddressRule implements Rule {
14+
15+
private final String PATTERN = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
16+
17+
@Override
18+
public RuleResult passes(Object value) {
19+
20+
if(!(value instanceof String))
21+
return RuleResult.reject();
22+
23+
return RuleResult.passes(Pattern.matches(PATTERN, String.valueOf(value)));
24+
}
25+
26+
@Override
27+
public String message(String field) {
28+
return String.format("The field \"%s\" needs to be a valid ip address", field);
29+
}
30+
}

0 commit comments

Comments
 (0)