added null checks to validator, created a bunch of junit tests

This commit is contained in:
augmentedpotato
2026-03-24 20:42:45 -06:00
parent 5b7c19f334
commit 4736b8bd3f
3 changed files with 253 additions and 5 deletions

View File

@@ -13,6 +13,7 @@ public class Validator {
if (value == null || value.isBlank()){
msg += name + " is required. \n";
}
return msg;
}
@@ -24,8 +25,13 @@ public class Validator {
*/
public static String isNonNegativeDouble(String value, String name){
String msg ="";
if (value == null) {
msg += name + " must be a number.\n";
return msg;
}
double result;
try{
try {
result = Double.parseDouble(value);
if (result < 0){
msg += name + " must be greater than or equal 0. \n";
@@ -34,6 +40,7 @@ public class Validator {
catch (NumberFormatException e){
msg += name + " must be a number.\n";
}
return msg;
}
@@ -47,8 +54,13 @@ public class Validator {
*/
public static String isDoubleInRange(String value, String name, double minValue, double maxValue){
String msg ="";
if (value == null) {
msg += name + " must be a number.\n";
return msg;
}
double result;
try{
try {
result = Double.parseDouble(value);
if (result < minValue || result > maxValue){
msg += name + " must be between " + minValue + " and " + maxValue + "\n";
@@ -57,6 +69,7 @@ public class Validator {
catch (NumberFormatException e){
msg += name + " must be a number.\n";
}
return msg;
}
@@ -69,7 +82,7 @@ public class Validator {
public static String isNonNegativeInteger(String value, String name){
String msg ="";
int result;
try{
try {
result = Integer.parseInt(value);
if (result < 0){
msg += name + " must be greater than or equal 0. \n";
@@ -78,6 +91,7 @@ public class Validator {
catch (NumberFormatException e){
msg += name + " must be a whole number.\n";
}
return msg;
}
@@ -90,9 +104,10 @@ public class Validator {
*/
public static String isLessThanVarChars(String value, String name, int length){
String msg ="";
if (value.length() > length){
if (value == null || value.length() > length){
msg += name + " must be less than " + length + " characters. \n";
}
return msg;
}
@@ -104,11 +119,17 @@ public class Validator {
*/
public static String isValidEmail(String value, String name){
String msg = "";
if (value == null) {
msg += name + " is not in a valid format. \n";
return msg;
}
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
if (!value.matches(regex)){
msg += name + " is not in a valid format. \n";
}
return msg;
}
@@ -120,11 +141,17 @@ public class Validator {
*/
public static String isValidPhoneNumber(String value, String name){
String msg = "";
if (value == null) {
msg += name + " must be in format XXX-XXX-XXXX. \n";
return msg;
}
String regex = "^\\d{3}-\\d{3}-\\d{4}$";
if (!value.matches(regex)){
msg += name + " must be in format XXX-XXX-XXXX. \n";
}
return msg;
}
}
}