diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100755 index 0000000..13c4629 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + 1.8 + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100755 index 0000000..c055b25 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100755 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100755 index 0000000..3543521 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100755 index 0000000..7973153 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,30 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 26 + defaultConfig { + applicationId "com.laurentiusimionescu.validator" + minSdkVersion 21 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:26.1.0' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.1' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' + + compile project(':validator') + +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100755 index 0000000..6e7ffa9 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ccad196 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/app/src/test/java/com/laurentiusimionescu/validator/ValidatorTest.java b/app/src/test/java/com/laurentiusimionescu/validator/ValidatorTest.java new file mode 100755 index 0000000..a451e98 --- /dev/null +++ b/app/src/test/java/com/laurentiusimionescu/validator/ValidatorTest.java @@ -0,0 +1,121 @@ +package com.laurentiusimionescu.validator; + +import org.junit.Test; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; + +public class ValidatorTest { + + @Test + public void testNullString() { + + Example example = new Example(); + + assertFalse(ValidationProcessor.isValid(example)); + } + + @Test + public void testEmptyString() { + + Example example = new Example(); + + assertFalse(ValidationProcessor.isValid(example)); + } + + + @Test + public void testAllGood() { + Example example = new Example(); + example.dog = "Dog"; + example.boo = 12; + example.innerClass = new InnerClass(); + example.innerClass.innerString = "i1"; + + example.innerClass3 = new InnerClass(); + example.innerClass3.innerString = "i3"; + + example.castClass = new CastClass(); + example.castClass.castClass = new CastClass(); + + + assertTrue(ValidationProcessor.getMessage(example), ValidationProcessor.isValid(example)); + + } + + @Test + public void testInteger() { + Example example = new Example(); + + + assertFalse(ValidationProcessor.isValid(example)); + + } + + @Test + public void testDouble() { + Example example = new Example(); + + assertFalse(ValidationProcessor.isValid(example)); + + } + + + public class Example { + + @ParamRequired + String dog; + + @ParamOptional(rule = ValidatorRule.EMAIL) + String email = "abc@gmail.com"; + + String foo; + + @ParamRequired + Integer boo; + + @ParamRequired + Integer boo2 = 90; + + @ParamRequired + InnerClass innerClass; + + InnerClass innerClass2; + + @ParamRequired + InnerClass innerClass3 = new InnerClass(); + + @ParamOptional + CastClass castClass; + + } + + class InnerClass { + + @ParamRequired + String innerString; + + } + + class CastClass { + + @ParamOptional(rule = ValidatorRule.EMAIL) + String name = "asdf@sdf.com"; + + @ParamOptional + CastClass castClass; + + } + + class Foo { + + @ParamRequired + String title; + + @ParamOptional + String description; + + } + + +} diff --git a/build.gradle b/build.gradle new file mode 100755 index 0000000..8d65c57 --- /dev/null +++ b/build.gradle @@ -0,0 +1,27 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.0.1' + + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100755 index 0000000..3530b01 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,17 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 0000000..febbc21 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jan 23 11:16:53 EET 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100755 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100755 index 0000000..f275c60 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':app', ':validator' diff --git a/validator/.gitignore b/validator/.gitignore new file mode 100755 index 0000000..3543521 --- /dev/null +++ b/validator/.gitignore @@ -0,0 +1 @@ +/build diff --git a/validator/build.gradle b/validator/build.gradle new file mode 100755 index 0000000..a750cff --- /dev/null +++ b/validator/build.gradle @@ -0,0 +1,34 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion 26 + + + + defaultConfig { + minSdkVersion 21 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + + implementation 'com.android.support:appcompat-v7:26.1.0' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.1' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' +} diff --git a/validator/proguard-rules.pro b/validator/proguard-rules.pro new file mode 100755 index 0000000..6e7ffa9 --- /dev/null +++ b/validator/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/validator/src/main/AndroidManifest.xml b/validator/src/main/AndroidManifest.xml new file mode 100755 index 0000000..584fca5 --- /dev/null +++ b/validator/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/validator/src/main/java/com/laurentiusimionescu/validator/ParamOptional.java b/validator/src/main/java/com/laurentiusimionescu/validator/ParamOptional.java new file mode 100755 index 0000000..64b3489 --- /dev/null +++ b/validator/src/main/java/com/laurentiusimionescu/validator/ParamOptional.java @@ -0,0 +1,21 @@ +package com.laurentiusimionescu.validator; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD}) +public @interface ParamOptional { + + /* Default is without regex. */ + String regex() default ""; + + /** + * Default rule is without a rule. + * Available rules: {@link ValidatorRule} + */ + ValidatorRule rule() default ValidatorRule.NO_RULE; + +} diff --git a/validator/src/main/java/com/laurentiusimionescu/validator/ParamRequired.java b/validator/src/main/java/com/laurentiusimionescu/validator/ParamRequired.java new file mode 100755 index 0000000..d324135 --- /dev/null +++ b/validator/src/main/java/com/laurentiusimionescu/validator/ParamRequired.java @@ -0,0 +1,21 @@ +package com.laurentiusimionescu.validator; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD}) +public @interface ParamRequired { + + /* Default is without regex. */ + String regex() default ""; + + /** + * Default rule is without a rule. + * Available rules: {@link ValidatorRule} + */ + ValidatorRule rule() default ValidatorRule.NO_RULE; + +} diff --git a/validator/src/main/java/com/laurentiusimionescu/validator/ValidationProcessor.java b/validator/src/main/java/com/laurentiusimionescu/validator/ValidationProcessor.java new file mode 100755 index 0000000..a7beead --- /dev/null +++ b/validator/src/main/java/com/laurentiusimionescu/validator/ValidationProcessor.java @@ -0,0 +1,164 @@ +package com.laurentiusimionescu.validator; + +import android.support.annotation.NonNull; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Pattern; + +public class ValidationProcessor { + + private static final String VALIDATION_FAIL_NULL = "is required and is null"; + private static final String VALIDATION_FAIL_EMPTY = "is required and is empty"; + private static final String VALIDATION_FAIL_REGEX = "doesn't match regex"; + private static final String VALIDATION_ERROR = "validation error"; + + public static boolean isValid(@NonNull Object object) { + if (object == null) { + throw new RuntimeException("Object cannot be null"); + } + try { + return checkIfValid(object, object.getClass().getSimpleName()) == null; + } catch (IllegalAccessException e) { + e.printStackTrace(); + return false; + } + } + + public static String getMessage(@NonNull Object object) { + try { + return checkIfValid(object, object.getClass().getSimpleName()); + } catch (IllegalAccessException e) { + e.printStackTrace(); + return VALIDATION_ERROR; + } + } + + /* This method returns the message if the object is not valid, else will return null if the object is valid. */ + private static String checkIfValid(@NonNull Object object, String path) throws IllegalAccessException { + String errorMessage = null; + + for (Field field : object.getClass().getDeclaredFields()) { + field.setAccessible(true); + Object value = field.get(object); + + if (field.isAnnotationPresent(ParamRequired.class) && field.isAnnotationPresent(ParamOptional.class)) { + throw new RuntimeException("A field cannot be annotated with both ParamRequired and ParamOptional. Please remove one."); + } + + if (value != null && field.getClass().getDeclaredFields() != null && field.getClass().getDeclaredFields().length > 0 && !getWrapperTypes().contains(value.getClass())) { + String message = checkIfValid(value, path + "." + value.getClass().getSimpleName()); + if (message != null) { + errorMessage = message; + return errorMessage; + } + } + + if (field.isAnnotationPresent(ParamRequired.class)) { + errorMessage = requiredCheck(object, field, path); + if (errorMessage != null) { + return errorMessage; + } + } + + if (field.isAnnotationPresent(ParamOptional.class)) { + errorMessage = optionalCheck(object, field, path); + if (errorMessage != null) { + return errorMessage; + } + } + + } + + return errorMessage; + } + + private static String requiredCheck(@NonNull Object object, Field field, @NonNull String path) throws IllegalAccessException { + Object value = field.get(object); + + if (value == null) { + return path + "." + field.getName() + " " + VALIDATION_FAIL_NULL; + } + + if (value instanceof String && ((String) value).isEmpty()) { + return path + "." + field.getName() + " " + VALIDATION_FAIL_EMPTY; + } + + if (value instanceof String && !((String) value).isEmpty()) { + return regexCheckRequired((String) value, field, path); + } + + return null; + + } + + private static String optionalCheck(@NonNull Object object, Field field, @NonNull String path) throws IllegalAccessException { + Object value = field.get(object); + + if (value instanceof String && !((String) value).isEmpty()) { + return regexCheckOptional((String) value, field, path); + } + + return null; + + } + + + private static String regexCheckRequired(@NonNull String value, Field field, @NonNull String path) throws IllegalAccessException { + ParamRequired paramRequired = field.getAnnotation(ParamRequired.class); + + if (paramRequired.rule() != ValidatorRule.NO_RULE && !paramRequired.regex().isEmpty()) { + throw new RuntimeException("Choose only a regex or a predefined rule."); + } + + if (paramRequired.rule() != ValidatorRule.NO_RULE) { + if (!Pattern.compile(paramRequired.rule().getRegex(), Pattern.CASE_INSENSITIVE).matcher(value).find()) { + return path + "." + field.getName() + " is required and " + VALIDATION_FAIL_REGEX + " : " + paramRequired.rule().getRegex(); + } + } else { + if (!Pattern.compile(paramRequired.regex(), Pattern.CASE_INSENSITIVE).matcher(value).find()) { + return path + "." + field.getName() + " is required and " + VALIDATION_FAIL_REGEX + " : " + paramRequired.regex(); + } + } + + return null; + } + + private static String regexCheckOptional(@NonNull String value, Field field, @NonNull String path) throws IllegalAccessException { + ParamOptional paramOptional = field.getAnnotation(ParamOptional.class); + + if (paramOptional.rule() != ValidatorRule.NO_RULE && !paramOptional.regex().isEmpty()) { + throw new RuntimeException("Choose only a regex or a predefined rule."); + } + + if (paramOptional.rule() != ValidatorRule.NO_RULE) { + if (!Pattern.compile(paramOptional.rule().getRegex(), Pattern.CASE_INSENSITIVE).matcher(value).find()) { + return path + "." + field.getName() + " is optional but " + VALIDATION_FAIL_REGEX + " : " + paramOptional.rule().getRegex(); + } + } else { + if (!Pattern.compile(paramOptional.regex(), Pattern.CASE_INSENSITIVE).matcher(value).find()) { + return path + "." + field.getName() + " is optional but " + VALIDATION_FAIL_REGEX + " : " + paramOptional.regex(); + } + } + + return null; + } + + private static Set> getWrapperTypes() { + Set> ret = new HashSet>(); + ret.add(Boolean.class); + ret.add(Character.class); + ret.add(Byte.class); + ret.add(Short.class); + ret.add(Integer.class); + ret.add(Long.class); + ret.add(Float.class); + ret.add(Double.class); + ret.add(Void.class); + ret.add(String.class); + return ret; + } + + +} diff --git a/validator/src/main/java/com/laurentiusimionescu/validator/ValidatorRule.java b/validator/src/main/java/com/laurentiusimionescu/validator/ValidatorRule.java new file mode 100755 index 0000000..238475f --- /dev/null +++ b/validator/src/main/java/com/laurentiusimionescu/validator/ValidatorRule.java @@ -0,0 +1,72 @@ +package com.laurentiusimionescu.validator; + +public enum ValidatorRule { + + /* A rule represents a predefined regex. The most common regex are for: email and password. + To use a custom regex type it in the Annotation Eg. @ParamOptional(regex = "abc") */ + + NO_RULE(null), // default rule + + CREDIT_CARD("^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$"), // This regular expression will validate all major credit cards: American Express (Amex), Discover, Mastercard, and Visa. Note that it is not quite as precise as its counterpart Perl and PHP regex. + CREDIT_CARD_VISA("^(4[0-9]{12}(?:[0-9]{3})?)*$"), + CREDIT_CARD_MASTERCARD("^(5[1-5][0-9]{14})*$"), + CREDIT_CARD_AMEX("^(3[47][0-9]{13})*$"), + + DATE_DD_MM_YYYY("^([1-9]|0[1-9]|[12][0-9]|3[01])\\D([1-9]|0[1-9]|1[012])\\D(19[0-9][0-9]|20[0-9][0-9])$"), // usual date format (dd mm yyyy, d/m/yyyy, etc.) + DATE_MM_DD_YYYY("^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$"), // Validate the calendar date in MM/DD/YYYY format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099. + DATE_YYYY_MM_DD("^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$"), // Validate the calendar date in YYYY/MM/DD format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099. + + EMAIL("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$"), + USERNAME("^[\\w\\d_.]{4,}$"), // Common username + + PASSWORD("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"), // complex password, look below for explanation + PASSWORD_6_CHAR("^.{6,}$"), // Simple password, enter 6 or more chars + + PHONE_NUMBER("^\\+?[\\d\\s]{3,}$"), + PHONE_NUMBER_WITH_CODE("^\\+?[\\d\\s]+\\(?[\\d\\s]{10,}$"), + PHONE_NUMBER_NORTH_AMERICA("^(([0-9]{1})*[- .(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4})+$"), // This regex will validate a 10-digit North American telephone number. Separators are not required, but can include spaces, hyphens, or periods. Parentheses around the area code are also optional. + + DIGITS_ONLY("^[0-9]+$"), + NUMBER_POSITIVE("^\\d*\\.?\\d+$"), + NUMBER_NEGATIVE("^-\\d*\\.?\\d+$"), + + ALPHA_NUMERIC("^[a-zA-Z0-9]*$"), // Alpha-numeric characters only + ALPHA_NUMERIC_WITH_SPACES("^[a-zA-Z0-9 ]*$"), // Alpha-numeric characters with spaces only + ALPHABETIC("^[a-zA-Z]*$"), // Alphabetic characters only + ALPHABETIC_UPPERCASE("^([A-Z])*$"), // Uppercase letters only + ALPHABETIC_LOWERCASE("^([a-z])*$"), // Lowercase letters only + + + DOMAIN("^([a-z][a-z0-9-]+(\\.|-*\\.))+[a-z]{2,6}$"), + URL("^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"), + IP_V4("^(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]){3}$"), + + STATES_US("^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$"), // Validate all 2-letter US State abbreviates with this regular expression. + ZIP_CODE_US("^[0-9]{5}(?:-[0-9]{4})?$"), // This regexp verifies US ZIP Codes, with an optional 4 number ZIP code extension. + + POSTAL_CODE_CANADA("^[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]$"), // Canadian Postal Codes + POSTAL_CODE_UK("^([A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2})*$"), // This regexp verifies UK Postal Codes. + POSTAL_CODE_AUSTRALIA("^((0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2}))*$"); // If you need to verify Australian Postal Codes, use this regular expression. + + /** + * ^ # start-of-string + * (?=.*[0-9]) # a digit must occur at least once + * (?=.*[a-z]) # a lower case letter must occur at least once + * (?=.*[A-Z]) # an upper case letter must occur at least once + * (?=.*[@#$%^&+=]) # a special character must occur at least once + * (?=\S+$) # no whitespace allowed in the entire string + * .{8,} # anything, at least eight places though + * $ # end-of-string + */ + + private String regex; + + ValidatorRule(String regex) { + this.regex = regex; + } + + public String getRegex() { + return regex; + } + +}