So the service above returns our information in a form that we can use. We're essentially going to translate this information into the Regula framework. To do this, we need to write a tag. The tag goes through the gathered information and figures out the property name, the constraints attached to the property, and the parameters to the constraints. The tag also figures out the composing constraints for compound constraints and translates that to Regula compound-constraints:
generate-validation.tag:
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 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="string" uri="http://regula-spring" %> < c:if test = "${not empty propertyToConstraintInstancesMap or propertyToConstraintInstancesMap != null}" > < script type = "text/javascript" > jQuery(document).ready(function() { function generateRegulaConstraint(constraintName, params) { var constraintDefinitionString = ""; var parameterString = ""; for(var i = 0; i < params.length ; i++) { var param = params [i]; /* There are special cases that we handle here: o If the parameter is a message parameter and of the form {fully.qualified.name} then we ignore it o We look at the type property of the parameter and declare our parameter appropriately */ if(param.type != "String") { //if the parameter value is not a String type, then we can simply use param = value //UNLESS the parameter is a groups parameter and it is an empty array "[]" if(param.name != "groups" || param.name != "[]") { parameterString += (param.name + "=" + param.value + ", "); } } else { //if parameter value is a String type, we can simply use param = "value" EXCEPT if it is //a regular expression if(constraintName == "Pattern" && param.name == "regexp") { parameterString += (param.name + "=" + param.value + ", "); } else { parameterString += (param.name + "=\"" + param.value +"\", "); } } } parameterString = parameterString.replace(/, $/, ""); if(parameterString == "") { constraintDefinitionString = "@" + constraintName; } else { constraintDefinitionString = "@" + constraintName + "(" + parameterString + ")"; } return constraintDefinitionString; } var $ element = null ; var dataConstraintsAttribute = "" ; var fieldConstraints = "" ; var constraintName = "" ; var params = null ; <c:forEach items = "${propertyToConstraintInstancesMap}" var = "mapEntry" > < c:set var = "fieldName" value = "${mapEntry.key}" /> $element = jQuery("[name=${fieldName}]"); dataConstraintsAttribute = $element.attr("data-constraints"); fieldConstraints = ""; < c:forEach items = "${mapEntry.value}" var = "validationConstraint" > constraintName = "${validationConstraint.name}"; params = []; <%-- this insanity here is for TRIPLE escaping. JSTL -> Javascript -> HTML Attribute. If we only do a double escape we get valid Javascript, but since we're inserting this into an HTML attribute, we need to escape it once more --%> < c:set var = "search" value = "\" " /> < c:set var = "replace" value = "\\\\\\\" " /> < c:forEach items = "${validationConstraint.parameters}" var = "parameter" > < c:set var = "parameterValue" value = "${parameter.value}" /> < c:if test = "${parameter.name == 'message'}" > < fmt:message key = "${parameterValue}" var = "parameterValue" /> < c:if test = "${!fn:endsWith(parameterValue, '.')}" > < c:set var = "parameterValue" value = "${parameterValue}." /> </ c:if > </ c:if > params.push({name: "${parameter.name}", type: "${parameter.type}", value: "${fn:replace(parameterValue, search, replace)}"}); </ c:forEach > fieldConstraints += " " + generateRegulaConstraint(constraintName, params); </ c:forEach > if(dataConstraintsAttribute) { $element.attr("data-constraints", dataConstraintsAttribute + fieldConstraints); } else { $element.attr("data-constraints", fieldConstraints); } $element.addClass("regula-validation"); </ c:forEach > var compoundConstraintDefinitions = {}; var compoundConstraintDefinition = {}; var composingConstraints = []; var composingConstraint = {}; var composingConstraintParameters = []; var composingConstraintParameter = {}; < c:forEach items = "${compoundConstraintDefinitionSet}" var = "compoundConstraintDefinition" > < c:set var = "name" value = "${compoundConstraintDefinition.name}" /> < c:set var = "parameters" value = "" /> < c:forEach items = "${compoundConstraintDefinition.parameters}" var = "parameter" > < c:set var = "parameters" value = "${parameters}\" ${parameter}\"," /> </ c:forEach > < c:set var = "parameters" value = "${string:replaceUsingRegex(',$', '', parameters, '')}" /> compoundConstraintDefinition = {}; compoundConstraintDefinition["params"] = [${parameters}]; composingConstraints = []; < c:forEach items = "${compoundConstraintDefinition.composingConstraints}" var = "composingConstraint" > composingConstraint = {}; composingConstraint["name"] = "${composingConstraint.name}"; composingConstraintParameters = {}; < c:forEach items = "${composingConstraint.parameters}" var = "composingConstraintParameter" > composingConstraintParameters["name"] = "${composingConstraintParameter.name}"; < c:choose > < c:when test = "${composingConstraintParameter.type != 'String'}" > < c:choose > < c:when test = "${composingConstraintParameter.type == 'Array'}" > < c:set var = "value" value = "${fn:replace(composingConstraintParameter.value, '[', '')}" /> < c:set var = "value" value = "${fn:replace(value, ']', '')}" /> < c:set var = "groups" value = "" /> < c:forEach items = "${fn:split(value, ',')}" var = "group" > < c:set var = "groups" value = "${groups}regula.Group.${group}," /> </ c:forEach > < c:set var = "groups" value = "${string:replaceUsingRegex(',$', '', groups, '')}" /> composingConstraintParameters["${composingConstraintParameter.name}"] = [${groups}]; </ c:when > < c:otherwise > composingConstraintParameters["${composingConstraintParameter.name}"] = ${composingConstraintParameter.value}; </ c:otherwise > </ c:choose > </ c:when > < c:otherwise > composingConstraintParameters["${composingConstraintParameter.name}"] = "${composingConstraintParameter.value}"; </ c:otherwise > </ c:choose > </ c:forEach > composingConstraint["params"] = composingConstraintParameters; composingConstraints.push(composingConstraint); </ c:forEach > compoundConstraintDefinition["constraints"] = composingConstraints; compoundConstraintDefinitions["${name}"] = compoundConstraintDefinition; </ c:forEach > /* our compound constraints come in no particular order, and may have dependencies between them. This means that if we first encounter a constraint that has composing constraints that have NOT been defined, we have to define them first. A recursive algorithm is perfect for this */ for(var compoundConstraintName in compoundConstraintDefinitions) { if(compoundConstraintDefinitions.hasOwnProperty(compoundConstraintName)) { /* recursive self-invoked anonymous function that traverses the "dependency" tree */ (function(definition, name) { if(typeof regula.Constraint[name] == "undefined") { var constraints = []; for(var i = 0; i < definition.constraints.length ; i++) { var constraint = definition .constraints[i]; if(typeof regula.Constraint[constraint.name] == "undefined") { arguments.callee(compoundConstraintDefinitions[constraint.name], constraint.name); } var composingConstraint = {constraintType: regula.Constraint[constraint.name]}; if(typeof constraint.params != "undefined") { composingConstraint.params = constraint .params; } constraints.push(composingConstraint); } regula.compound({name: name, constraints: constraints}); } }(compoundConstraintDefinitions[compoundConstraintName], compoundConstraintName)); } } }); jQuery(document).ready(function() { regula.bind(); }); jQuery(document).ready(function() { jQuery("form").live("submit", function() { jQuery("span[id$=_error]").remove(); var validationResults = regula .validate(); for(var i = 0 ; i < validationResults.length; i++) { var validationResult = validationResults [i]; for(var j = 0 ; j < validationResult.failingElements.length; j++) { var failingElement = validationResult .failingElements[j]; var elementId = failingElement .id; var $ element = jQuery ("#" + elementId.replace(/\./g, "\\.")); $element.after("<span id=\"" + elementId.replace(/\./g, "\\.") + "_error\" style=\"color:#ff0000\">" + $element.text() + " " + validationResult.message + "</ span >"); } } return (validationResults.length == 0); }); }); </ script > </ c:if > |
This tag also takes care of binding the submit handler (using jQuery), which runs the validation on submit and displays error messages if any. If you need to do anything more complicated, you can override the submit handler.
That's pretty much it. In another blog post, I'll talk about actually using the integration.
Interesting, I hate spam, but I’m thinking of creating something similar to dumb ai where it ask fun question rather than the mono tone that we see today 🙁