|
1 | 1 | /*
|
2 |
| - * Copyright 2011-2013 Kevin Seim |
| 2 | + * Copyright 2011-2014 Kevin Seim |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
@@ -38,6 +38,9 @@ public class Field extends ParserComponent implements Property {
|
38 | 38 |
|
39 | 39 | private static final boolean USE_DEFAULT_IF_MISSING =
|
40 | 40 | Settings.getInstance().getBoolean(Settings.USE_DEFAULT_IF_MISSING);
|
| 41 | + |
| 42 | + private static final boolean VALIDATE_ON_MARSHAL = |
| 43 | + Settings.getInstance().getBoolean(Settings.VALIDATE_ON_MARSHAL); |
41 | 44 |
|
42 | 45 | private static final boolean marshalDefault =
|
43 | 46 | Settings.getInstance().getBoolean(Settings.DEFAULT_MARSHALLING_ENABLED);
|
@@ -194,6 +197,38 @@ public boolean marshal(MarshallingContext context) {
|
194 | 197 | text = formatValue(value);
|
195 | 198 | }
|
196 | 199 |
|
| 200 | + if (VALIDATE_ON_MARSHAL) { |
| 201 | + if (text == Value.NIL) { |
| 202 | + if (!format.isNillable()) { |
| 203 | + throw new InvalidBeanException("Invalid field '" + getName() + "', the value is not nillable"); |
| 204 | + } else if (required) { |
| 205 | + throw new InvalidBeanException("Invalid field '" + getName() + "', a value is required"); |
| 206 | + } |
| 207 | + } |
| 208 | + else if (text == null) { |
| 209 | + if (required) { |
| 210 | + throw new InvalidBeanException("Invalid field '" + getName() + "', a value is required"); |
| 211 | + } |
| 212 | + } |
| 213 | + else { |
| 214 | + // validate minimum length |
| 215 | + if (text.length() < minLength) { |
| 216 | + throw new InvalidBeanException("Invalid field '" + getName() + "', '" + |
| 217 | + text + "' does not meet minimum length of " + minLength); |
| 218 | + } |
| 219 | + // validate maximum length |
| 220 | + if (text.length() > maxLength) { |
| 221 | + throw new InvalidBeanException("Invalid field '" + getName() + "', '" + |
| 222 | + text + "' exceeds maximum length of " + maxLength); |
| 223 | + } |
| 224 | + // validate the regular expression |
| 225 | + if (regex != null && !regex.matcher(text).matches()) { |
| 226 | + throw new InvalidBeanException("Invalid field '" + getName() + "', '" + |
| 227 | + text + "' does not match pattern '" + regex.pattern() + "'"); |
| 228 | + } |
| 229 | + } |
| 230 | + } |
| 231 | + |
197 | 232 | format.insertField(context, text);
|
198 | 233 | return true;
|
199 | 234 | }
|
|
0 commit comments