/
ValidationTagLib.groovy
493 lines (448 loc) · 18.4 KB
/
ValidationTagLib.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.plugins.web.taglib
import grails.artefact.Artefact
import groovy.transform.CompileStatic
import groovy.xml.MarkupBuilder
import java.beans.PropertyEditor
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import org.apache.commons.lang.StringEscapeUtils
import org.codehaus.groovy.grails.support.encoding.CodecLookup
import org.codehaus.groovy.grails.support.encoding.Encoder
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
import org.codehaus.groovy.grails.web.taglib.GroovyPageAttributes
import org.springframework.beans.PropertyEditorRegistry
import org.springframework.context.MessageSource
import org.springframework.context.MessageSourceResolvable
import org.springframework.context.NoSuchMessageException
import org.springframework.context.support.DefaultMessageSourceResolvable
import org.springframework.validation.Errors
import org.springframework.web.context.request.RequestContextHolder
/**
* Tags to handle validation and errors.
*
* @author Graeme Rocher
*/
@Artefact("TagLibrary")
class ValidationTagLib {
static returnObjectForTags = ['message', 'fieldError', 'formatValue']
MessageSource messageSource
CodecLookup codecLookup
/**
* Renders an error message for the given bean and field.<br/>
*
* eg. <g:fieldError bean="${book}" field="title" />
*
* @attr bean REQUIRED The bean to check for errors
* @attr field REQUIRED The field of the bean or model reference to check
* @attr message The object to resolve the message for. Objects must implement org.springframework.context.MessageSourceResolvable.
* @attr encodeAs The name of a codec to apply, i.e. HTML, JavaScript, URL etc
* @attr locale override locale to use instead of the one detected
*/
Closure fieldError = { attrs, body ->
def bean = attrs.bean
def field = attrs.field
if (bean && field) {
if (bean.metaClass.hasProperty(bean, 'errors')) {
return messageImpl(error: bean.errors?.getFieldError(field), encodeAs: "HTML")
}
}
return ''
}
/**
* Obtains the value of a field either from the original errors.<br/>
*
* eg. <g:fieldValue bean="${book}" field="title" />
*
* @emptyTag
*
* @attr bean REQUIRED The bean to check for errors
* @attr field REQUIRED The field of the bean or model reference to check
*/
Closure fieldValue = { attrs, body ->
def bean = attrs.bean
String field = attrs.field?.toString()
if (!bean || !field) {
return
}
def tagSyntaxCall = (attrs instanceof GroovyPageAttributes) ? attrs.isGspTagSyntaxCall() : false
if (bean.metaClass.hasProperty(bean, 'errors')) {
Errors errors = bean.errors
def rejectedValue = errors?.getFieldError(field)?.rejectedValue
if (rejectedValue == null) {
rejectedValue = bean
for (String fieldPart in field.split("\\.")) {
rejectedValue = rejectedValue?."$fieldPart"
}
}
if (rejectedValue != null) {
out << formatValue(rejectedValue, field, tagSyntaxCall)
}
}
else {
def rejectedValue = bean
for (String fieldPart in field.split("\\.")) {
rejectedValue = rejectedValue?."$fieldPart"
}
if (rejectedValue != null) {
out << formatValue(rejectedValue, field, tagSyntaxCall)
}
}
}
def extractErrors(attrs) {
def model = attrs.model
def checkList = []
if (attrs.containsKey('bean')) {
if (attrs.bean) {
checkList << attrs.bean
}
}
else if (attrs.containsKey('model')) {
if (model) {
checkList = model.findAll {it.value?.errors instanceof Errors}.collect {it.value}
}
}
else {
for (attributeName in request.attributeNames) {
def ra = request[attributeName]
if (ra) {
def mc = GroovySystem.metaClassRegistry.getMetaClass(ra.getClass())
if (ra instanceof Errors && !checkList.contains(ra)) {
checkList << ra
}
else if (mc.hasProperty(ra, 'errors') && ra.errors instanceof Errors && !checkList.contains(ra.errors)) {
checkList << ra.errors
}
}
}
}
def resultErrorsList = []
for (i in checkList) {
def errors = null
if (i instanceof Errors) {
errors = i
}
else {
def mc = GroovySystem.metaClassRegistry.getMetaClass(i.getClass())
if (mc.hasProperty(i, 'errors')) {
errors = i.errors
}
}
if (errors?.hasErrors()) {
// if the 'field' attribute is not provided then we should output a body,
// otherwise we should check for field-specific errors
if (!attrs.field || errors.hasFieldErrors(attrs.field)) {
resultErrorsList << errors
}
}
}
resultErrorsList
}
/**
* Checks if the request has errors either for a field or global errors.
*
* @attr bean The bean to check for errors
* @attr field The field of the bean or model reference to check
* @attr model The model reference to check for errors
*/
Closure hasErrors = { attrs, body ->
def errorsList = extractErrors(attrs)
if (errorsList) {
out << body()
}
}
/**
* Loops through each error of the specified bean or model. If no arguments
* are specified it will go through all model attributes and check for errors.
*
* @attr bean The bean to check for errors
* @attr field The field of the bean or model reference to check
* @attr model The model reference to check for errors
*/
Closure eachError = { attrs, body ->
eachErrorInternal(attrs, body, true)
}
def eachErrorInternal(attrs, body, boolean outputResult = false) {
def errorsList = extractErrors(attrs)
eachErrorInternalForList attrs, errorsList, body, outputResult
}
def eachErrorInternalForList(attrs, errorsList, body, boolean outputResult = false) {
def var = attrs.var
def field = attrs.field
def errorList = []
for (errors in errorsList) {
if (field) {
if (errors.hasFieldErrors(field)) {
errorList += errors.getFieldErrors(field)
}
}
else {
errorList += errors.allErrors
}
}
for (error in errorList) {
def result
if (var) {
result = body([(var):error])
}
else {
result = body(error)
}
if (outputResult) {
out << result
}
}
null
}
/**
* Loops through each error and renders it using one of the supported mechanisms (defaults to "list" if unsupported).
*
* @emptyTag
*
* @attr bean The bean to check for errors
* @attr field The field of the bean or model reference to check
* @attr model The model reference to check for errors
*/
Closure renderErrors = { attrs, body ->
def renderAs = attrs.remove('as') ?: 'list'
if (renderAs == 'list') {
def codec = attrs.codec ?: 'HTML'
if (codec == 'none') codec = ''
def errorsList = extractErrors(attrs)
if (errorsList) {
out << "<ul>"
out << eachErrorInternalForList(attrs, errorsList, {
out << "<li>${message(error:it, encodeAs:codec)}</li>"
})
out << "</ul>"
}
}
else if (renderAs.equalsIgnoreCase("xml")) {
def mkp = new MarkupBuilder(out)
mkp.errors() {
eachErrorInternal(attrs, {
error(object: it.objectName,
field: it.field,
message: message(error:it)?.toString(),
'rejected-value': StringEscapeUtils.escapeXml(it.rejectedValue))
})
}
}
}
/**
* Resolves a message code for a given error or code from the resource bundle.
*
* @emptyTag
*
* @attr error The error to resolve the message for. Used for built-in Grails messages.
* @attr message The object to resolve the message for. Objects must implement org.springframework.context.MessageSourceResolvable.
* @attr code The code to resolve the message for. Used for custom application messages.
* @attr args A list of argument values to apply to the message, when code is used.
* @attr default The default message to output if the error or code cannot be found in messages.properties.
* @attr encodeAs The name of a codec to apply, i.e. HTML, JavaScript, URL etc
* @attr locale override locale to use instead of the one detected
*/
Closure message = { attrs ->
messageImpl(attrs)
}
@CompileStatic
def messageImpl(Map attrs) {
Locale locale = FormatTagLib.resolveLocale(attrs.locale)
def tagSyntaxCall = (attrs instanceof GroovyPageAttributes) ? attrs.isGspTagSyntaxCall() : false
def text
Object error = attrs.error ?: attrs.message
if (error) {
if (!attrs.encodeAs && error instanceof MessageSourceResolvable) {
MessageSourceResolvable errorResolvable = (MessageSourceResolvable)error
if (errorResolvable.arguments) {
error = new DefaultMessageSourceResolvable(errorResolvable.codes, encodeArgsIfRequired(errorResolvable.arguments) as Object[], errorResolvable.defaultMessage)
}
}
try {
if (error instanceof MessageSourceResolvable) {
text = messageSource.getMessage(error, locale)
} else {
text = messageSource.getMessage(error.toString(), null, locale)
}
}
catch (NoSuchMessageException e) {
if (error instanceof MessageSourceResolvable) {
text = ((MessageSourceResolvable)error).codes[0]
}
else {
text = error?.toString()
}
}
}
else if (attrs.code) {
String code = attrs.code?.toString()
List args = []
if (attrs.args) {
args = attrs.encodeAs ? attrs.args as List : encodeArgsIfRequired(attrs.args)
}
String defaultMessage
if (attrs.containsKey('default')) {
defaultMessage = attrs['default']?.toString()
} else {
defaultMessage = code
}
def message = messageSource.getMessage(code, args == null ? null : args.toArray(),
defaultMessage, locale)
if (message != null) {
text = message
}
else {
text = defaultMessage
}
}
if (text) {
Encoder encoder = codecLookup.lookupEncoder(attrs.encodeAs?.toString() ?: 'raw')
return encoder ? encoder.encode(text) : text
}
''
}
@CompileStatic
private List encodeArgsIfRequired(arguments) {
arguments.collect { value ->
if (value == null || value instanceof Number || value instanceof Date) {
value
} else {
Encoder encoder = codecLookup.lookupEncoder('HTML')
encoder ? encoder.encode(value) : value
}
}
}
// Maps out how Grails contraints map to Apache commons validators
static CONSTRAINT_TYPE_MAP = [email : 'email',
creditCard : 'creditCard',
matches : 'mask',
blank: 'required',
nullable: 'required',
maxSize: 'maxLength',
minSize: 'minLength',
range: 'intRange',
size: 'intRange',
length: 'maxLength,minLength']
/**
* Validates a form using Apache commons validator javascript against constraints defined in a Grails
* domain class.<br/>
*
* TODO: This tag is a work in progress
*
* @attr form REQUIRED the HTML form name
* @attr againstClass REQUIRED the domain class name
*/
Closure validate = { attrs, body ->
def form = attrs.form
if (!form) {
throwTagError("Tag [validate] is missing required attribute [form]")
}
def againstClass = attrs.against ?: form.substring(0,1).toUpperCase() + form.substring(1)
def dc = grailsAttributes.grailsApplication.getDomainClass(againstClass)
if (!dc) {
throwTagError("Tag [validate] could not find a domain class to validate against for name [${againstClass}]")
}
def appliedConstraints = []
dc.constrainedProperties.values().each {
appliedConstraints += it.collect{ it.appliedConstraints }
}
appliedConstraints = appliedConstraints.flatten()
def fieldValidations = [:]
appliedConstraints.each {
def validateType = CONSTRAINT_TYPE_MAP[it.name]
if (validateType) {
if (fieldValidations[validateType]) {
fieldValidations[validateType] << it
}
else {
fieldValidations[validateType] = [it]
}
}
}
out << '<script type="text/javascript">\n'
fieldValidations.each { k,v ->
def validateType = k
if (validateType) {
def validateTypes = [validateType]
if (validateType.contains(",")) {
validateTypes = validateType.split(",")
}
for (vt in validateTypes) {
// import required script
def scriptName = "org/apache/commons/validator/javascript/validate" + vt.substring(0,1).toUpperCase() + vt.substring(1) + ".js"
def inStream = getClass().classLoader.getResourceAsStream(scriptName)
if (inStream) {
out << inStream.getText('UTF-8')
}
out << "function ${form}_${vt}() {"
for (constraint in v) {
out << "this.${constraint.propertyName} = new Array("
out << "document.forms['${form}'].elements['${constraint.propertyName}']," // the field
out << '"Test message"' // TODO: Resolve the actual message
switch (vt) {
case 'mask': out << ",function() { return '${constraint.regex}'; }";break
case 'intRange': out << ",function() { if (arguments[0]=='min') return ${constraint.range.from}; else return ${constraint.range.to} }";break
case 'floatRange': out << ",function() { if (arguments[0]=='min') return ${constraint.range.from}; else return ${constraint.range.to} }";break
case 'maxLength': out << ",function() { return ${constraint.maxSize}; }";break
case 'minLength': out << ",function() { return ${constraint.minSize}; }";break
}
out << ');\n'
}
out << "}\n"
}
}
}
out << 'function validateForm(form) {\n'
fieldValidations.each { k,v ->
def validateType = k.substring(0,1).toUpperCase() + k.substring(1)
out << "if (!validate${validateType}(form)) return false;\n"
}
out << 'return true;\n'
out << '}\n'
// out << "document.forms['${attrs.form}'].onsubmit = function(e) {return validateForm(this)}\n"
out << '</script>'
}
/**
* Formats a given value for output to an HTML page by converting
* it to a string and encoding it. If the value is a number, it is
* formatted according to the current user's locale during the
* conversion to a string.
*/
def formatValue(value, String propertyPath = null, Boolean tagSyntaxCall = false) {
def webRequest = GrailsWebRequest.lookup()
PropertyEditorRegistry registry = webRequest.getPropertyEditorRegistry()
PropertyEditor editor = registry.findCustomEditor(value.getClass(), propertyPath)
if (editor) {
editor.setValue(value)
return !(value instanceof Number) ? editor.asText?.encodeAsHTML() : editor.asText
}
if (value instanceof Number) {
def pattern = "0"
if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) {
pattern = "0.00#####"
}
def locale = webRequest.getLocale()
def dcfs = locale ? new DecimalFormatSymbols(locale) : new DecimalFormatSymbols()
def decimalFormat = new DecimalFormat(pattern, dcfs)
value = decimalFormat.format(value)
}
if (value instanceof MessageSourceResolvable) {
value = message(message: value)
}
return value.toString().encodeAsHTML()
}
}