1 16 17 package org.springframework.validation; 18 19 import org.apache.commons.logging.Log; 20 import org.apache.commons.logging.LogFactory; 21 22 import org.springframework.util.Assert; 23 import org.springframework.util.StringUtils; 24 25 38 public abstract class ValidationUtils { 39 40 private static Log logger = LogFactory.getLog(ValidationUtils.class); 41 42 43 53 public static void invokeValidator(Validator validator, Object obj, Errors errors) { 54 Assert.notNull(validator, "Validator must not be null"); 55 Assert.notNull(errors, "Errors object must not be null"); 56 if (logger.isDebugEnabled()) { 57 logger.debug("Invoking validator [" + validator + "]"); 58 } 59 if (obj != null && !validator.supports(obj.getClass())) { 60 throw new IllegalArgumentException ("Validator " + validator.getClass() + 61 " does not support " + obj.getClass()); 62 } 63 validator.validate(obj, errors); 64 if (logger.isDebugEnabled()) { 65 if (errors.hasErrors()) { 66 logger.debug("Validator found " + errors.getErrorCount() + " errors"); 67 } 68 else { 69 logger.debug("Validator found no errors"); 70 } 71 } 72 } 73 74 85 public static void rejectIfEmpty(Errors errors, String field, String errorCode) { 86 rejectIfEmpty(errors, field, errorCode, null, null); 87 } 88 89 102 public static void rejectIfEmpty(Errors errors, String field, String errorCode, String defaultMessage) { 103 rejectIfEmpty(errors, field, errorCode, null, defaultMessage); 104 } 105 106 121 public static void rejectIfEmpty( 122 Errors errors, String field, String errorCode, Object [] errorArgs, String defaultMessage) { 123 124 Assert.notNull(errors, "Errors object must not be null"); 125 Object value = errors.getFieldValue(field); 126 if (value == null || !StringUtils.hasLength(value.toString())) { 127 errors.rejectValue(field, errorCode, errorArgs, defaultMessage); 128 } 129 } 130 131 143 public static void rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode) { 144 rejectIfEmptyOrWhitespace(errors, field, errorCode, null, null); 145 } 146 147 160 public static void rejectIfEmptyOrWhitespace( 161 Errors errors, String field, String errorCode, String defaultMessage) { 162 163 rejectIfEmptyOrWhitespace(errors, field, errorCode, null, defaultMessage); 164 } 165 166 181 public static void rejectIfEmptyOrWhitespace( 182 Errors errors, String field, String errorCode, Object [] errorArgs, String defaultMessage) { 183 184 Assert.notNull(errors, "Errors object must not be null"); 185 Object value = errors.getFieldValue(field); 186 if (value == null ||!StringUtils.hasText(value.toString())) { 187 errors.rejectValue(field, errorCode, errorArgs, defaultMessage); 188 } 189 } 190 191 } 192 | Popular Tags |