List of usage examples for org.apache.commons.validator Field getKey
public String getKey()
From source file:org.apache.struts.validator.FieldChecks.java
/** * Checks if the field's length is greater than or equal to the minimum * value. A <code>Null</code> will be considered an error. * * @param bean The bean validation is being performed on. * @param va The <code>ValidatorAction</code> that is currently * being performed./*from w ww . j ava 2 s . c o m*/ * @param field The <code>Field</code> object associated with the * current field being validated. * @param errors The <code>ActionMessages</code> object to add errors * to if any validation errors occur. * @param validator The <code>Validator</code> instance, used to access * other field values. * @param request Current request object. * @return True if stated conditions met. */ public static boolean validateMinLength(Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator, HttpServletRequest request) { String value = null; value = evaluateBean(bean, field); if (!GenericValidator.isBlankOrNull(value)) { try { String minVar = Resources.getVarValue("minlength", field, validator, request, true); int min = Integer.parseInt(minVar); boolean isValid = false; String endLth = Resources.getVarValue("lineEndLength", field, validator, request, false); if (GenericValidator.isBlankOrNull(endLth)) { isValid = GenericValidator.minLength(value, min); } else { isValid = GenericValidator.minLength(value, min, Integer.parseInt(endLth)); } if (!isValid) { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } } catch (Exception e) { processFailure(errors, field, "minlength", e); return false; } } return true; }
From source file:org.apache.struts.validator.FieldChecks.java
/** * Checks if a field has a valid url. Four optional variables can be * specified to configure url validation. * * <ul>/*from ww w . j a v a2 s.c o m*/ * * <li>Variable <code>allow2slashes</code> can be set to <code>true</code> * or <code>false</code> to control whether two slashes are allowed - * default is <code>false</code> (i.e. two slashes are NOT allowed).</li> * * <li>Variable <code>nofragments</code> can be set to <code>true</code> * or <code>false</code> to control whether fragments are allowed - * default is <code>false</code> (i.e. fragments ARE allowed).</li> * * <li>Variable <code>allowallschemes</code> can be set to * <code>true</code> or <code>false</code> to control if all schemes are * allowed - default is <code>false</code> (i.e. all schemes are NOT * allowed).</li> * * <li>Variable <code>schemes</code> can be set to a comma delimited list * of valid schemes. This value is ignored if <code>allowallschemes</code> * is set to <code>true</code>. Default schemes allowed are "http", * "https" and "ftp" if this variable is not specified.</li> * * </ul> * * @param bean The bean validation is being performed on. * @param va The <code>ValidatorAction</code> that is currently * being performed. * @param field The <code>Field</code> object associated with the * current field being validated. * @param errors The <code>ActionMessages</code> object to add errors * to if any validation errors occur. * @param validator The <code>Validator</code> instance, used to access * other field values. * @param request Current request object. * @return True if valid, false otherwise. */ public static boolean validateUrl(Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator, HttpServletRequest request) { String value = null; value = evaluateBean(bean, field); if (GenericValidator.isBlankOrNull(value)) { return true; } // Get the options and schemes Vars String allowallschemesVar = Resources.getVarValue("allowallschemes", field, validator, request, false); boolean allowallschemes = "true".equalsIgnoreCase(allowallschemesVar); int options = allowallschemes ? UrlValidator.ALLOW_ALL_SCHEMES : 0; String allow2slashesVar = Resources.getVarValue("allow2slashes", field, validator, request, false); if ("true".equalsIgnoreCase(allow2slashesVar)) { options += UrlValidator.ALLOW_2_SLASHES; } String nofragmentsVar = Resources.getVarValue("nofragments", field, validator, request, false); if ("true".equalsIgnoreCase(nofragmentsVar)) { options += UrlValidator.NO_FRAGMENTS; } String schemesVar = allowallschemes ? null : Resources.getVarValue("schemes", field, validator, request, false); // No options or schemes - use GenericValidator as default if ((options == 0) && (schemesVar == null)) { if (GenericValidator.isUrl(value)) { return true; } else { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } } // Parse comma delimited list of schemes into a String[] String[] schemes = null; if (schemesVar != null) { StringTokenizer st = new StringTokenizer(schemesVar, ","); schemes = new String[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { schemes[i++] = st.nextToken().trim(); } } // Create UrlValidator and validate with options/schemes UrlValidator urlValidator = new UrlValidator(schemes, options); if (urlValidator.isValid(value)) { return true; } else { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } }
From source file:org.apache.struts.validator.FieldChecks.java
/** * Process a validation failure.//from w ww . j a v a 2s . c o m */ private static void processFailure(ActionMessages errors, Field field, String validator, Throwable t) { // Log the error String logErrorMsg = sysmsgs.getMessage("validation.failed", validator, field.getProperty(), t.toString()); log.error(logErrorMsg); // Add general "system error" message to show to the user String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); }
From source file:org.apache.struts.validator.validwhen.ValidWhen.java
/** * Checks if the field matches the boolean expression specified in * <code>test</code> parameter. * * @param bean The bean validation is being performed on. * @param va The <code>ValidatorAction</code> that is currently being * performed.//w ww . j a va2 s. c o m * @param field The <code>Field</code> object associated with the * current field being validated. * @param errors The <code>ActionMessages</code> object to add errors to * if any validation errors occur. * @param request Current request object. * @return <code>true</code> if meets stated requirements, * <code>false</code> otherwise. */ public static boolean validateValidWhen(Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator, HttpServletRequest request) { Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null; boolean valid = false; int index = -1; if (field.isIndexed()) { String key = field.getKey(); final int leftBracket = key.indexOf("["); final int rightBracket = key.indexOf("]"); if ((leftBracket > -1) && (rightBracket > -1)) { index = Integer.parseInt(key.substring(leftBracket + 1, rightBracket)); } } if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } String test = null; try { test = Resources.getVarValue("test", field, validator, request, true); } catch (IllegalArgumentException ex) { String logErrorMsg = sysmsgs.getMessage("validation.failed", "validwhen", field.getProperty(), ex.toString()); log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } // Create the Lexer ValidWhenLexer lexer = null; try { lexer = new ValidWhenLexer(new StringReader(test)); } catch (Exception ex) { String logErrorMsg = "ValidWhenLexer Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } // Create the Parser ValidWhenParser parser = null; try { parser = new ValidWhenParser(lexer); } catch (Exception ex) { String logErrorMsg = "ValidWhenParser Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } parser.setForm(form); parser.setIndex(index); parser.setValue(value); try { parser.expression(); valid = parser.getResult(); } catch (Exception ex) { String logErrorMsg = "ValidWhen Error for field ' " + field.getKey() + "' - " + ex; log.error(logErrorMsg); String userErrorMsg = sysmsgs.getMessage("system.error"); errors.add(field.getKey(), new ActionMessage(userErrorMsg, false)); return false; } if (!valid) { errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field)); return false; } return true; }
From source file:org.apache.velocity.tools.struts.ValidatorTool.java
/** * Generates the dynamic JavaScript for the form. * * @param resources the validator resources * @param locale the locale for the current request * @param form the form to generate javascript for * @return the dynamic javascript/*from ww w.ja v a2 s. com*/ */ protected String getDynamicJavascript(ValidatorResources resources, Locale locale, Form form) { StringBuffer results = new StringBuffer(); MessageResources messages = StrutsUtils.getMessageResources(request, app); List actions = createActionList(resources, form); final String methods = createMethods(actions); String formName = form.getName(); jsFormName = formName; if (jsFormName.charAt(0) == '/') { String mappingName = StrutsUtils.getActionMappingName(jsFormName); ModuleConfig mconfig = ModuleUtils.getInstance().getModuleConfig(request, app); ActionConfig mapping = (ActionConfig) mconfig.findActionConfig(mappingName); if (mapping == null) { throw new NullPointerException("Cannot retrieve mapping for action " + mappingName); } jsFormName = mapping.getAttribute(); } results.append(getJavascriptBegin(methods)); for (Iterator i = actions.iterator(); i.hasNext();) { ValidatorAction va = (ValidatorAction) i.next(); int jscriptVar = 0; String functionName = null; if (va.getJsFunctionName() != null && va.getJsFunctionName().length() > 0) { functionName = va.getJsFunctionName(); } else { functionName = va.getName(); } results.append(" function "); results.append(jsFormName); results.append("_"); results.append(functionName); results.append(" () { \n"); for (Iterator x = form.getFields().iterator(); x.hasNext();) { Field field = (Field) x.next(); // Skip indexed fields for now until there is // a good way to handle error messages (and the length // of the list (could retrieve from scope?)) if (field.isIndexed() || field.getPage() != page || !field.isDependency(va.getName())) { continue; } String message = Resources.getMessage(messages, locale, va, field); message = (message != null) ? message : ""; //jscriptVar = this.getNextVar(jscriptVar); results.append(" this.a"); results.append(jscriptVar++); results.append(" = new Array(\""); results.append(field.getKey()); // TODO: escape? results.append("\", \""); results.append(escapeJavascript(message)); results.append("\", "); results.append("new Function (\"varName\", \""); Map vars = field.getVars(); // Loop through the field's variables. Iterator varsIterator = vars.keySet().iterator(); while (varsIterator.hasNext()) { String varName = (String) varsIterator.next(); // TODO: escape? Var var = (Var) vars.get(varName); String varValue = var.getValue(); String jsType = var.getJsType(); // skip requiredif variables field, fieldIndexed, fieldTest, fieldValue if (varName.startsWith("field")) { continue; } // these are appended no matter what jsType is results.append("this."); results.append(varName); String escapedVarValue = escapeJavascript(varValue); if (Var.JSTYPE_INT.equalsIgnoreCase(jsType)) { results.append("="); results.append(escapedVarValue); results.append("; "); } else if (Var.JSTYPE_REGEXP.equalsIgnoreCase(jsType)) { results.append("=/"); results.append(escapedVarValue); results.append("/; "); } else if (Var.JSTYPE_STRING.equalsIgnoreCase(jsType)) { results.append("='"); results.append(escapedVarValue); results.append("'; "); } // So everyone using the latest format // doesn't need to change their xml files immediately. else if ("mask".equalsIgnoreCase(varName)) { results.append("=/"); results.append(escapedVarValue); results.append("/; "); } else { results.append("='"); results.append(escapedVarValue); results.append("'; "); } } results.append(" return this[varName];\"));\n"); } results.append(" } \n\n"); } return results.toString(); }
From source file:org.caofei.taglib.html.JavascriptValidatorTag.java
/** * Generates the dynamic JavaScript for the form. * * @param config//from www .j av a 2 s .c o m * @param resources * @param locale * @param form */ private String createDynamicJavascript(ValidatorResources resources, Locale locale, Form form) throws JspException { StringBuffer results = new StringBuffer(); /* MessageResources messages = TagUtils.getInstance().retrieveMessageResources(pageContext, bundle, true); */ HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); ServletContext application = pageContext.getServletContext(); List actions = this.createActionList(resources, form); final String methods = this.createMethods(actions, this.stopOnError()); String formName = form.getName(); jsFormName = formName; /* if (jsFormName.charAt(0) == '/') { String mappingName = TagUtils.getInstance().getActionMappingName(jsFormName); ActionMapping mapping = (ActionMapping) config.findActionConfig(mappingName); if (mapping == null) { JspException e = new JspException(messages.getMessage("formTag.mapping", mappingName)); pageContext.setAttribute(Globals.EXCEPTION_KEY, e, PageContext.REQUEST_SCOPE); throw e; } jsFormName = mapping.getAttribute(); } */ results.append(this.getJavascriptBegin(methods)); for (Iterator i = actions.iterator(); i.hasNext();) { ValidatorAction va = (ValidatorAction) i.next(); int jscriptVar = 0; String functionName = null; if ((va.getJsFunctionName() != null) && (va.getJsFunctionName().length() > 0)) { functionName = va.getJsFunctionName(); } else { functionName = va.getName(); } results.append(" function " + jsFormName + "_" + functionName + " () { \n"); for (Iterator x = form.getFields().iterator(); x.hasNext();) { Field field = (Field) x.next(); // Skip indexed fields for now until there is a good way to // handle error messages (and the length of the list (could // retrieve from scope?)) if (field.isIndexed() || (field.getPage() != page) || !field.isDependency(va.getName())) { continue; } String message = null; /* Resources.getMessage(application, request, messages, locale, va, field); */ message = (message != null) ? message : ""; // prefix variable with 'a' to make it a legal identifier results.append(" this.a" + jscriptVar++ + " = new Array(\"" + field.getKey() + "\", \"" + escapeQuotes(message) + "\", "); results.append("new Function (\"varName\", \""); Map vars = field.getVars(); // Loop through the field's variables. Iterator varsIterator = vars.keySet().iterator(); while (varsIterator.hasNext()) { String varName = (String) varsIterator.next(); Var var = (Var) vars.get(varName); String varValue = null; /* Resources.getVarValue(var, application, request, false); */ String jsType = var.getJsType(); // skip requiredif variables field, fieldIndexed, fieldTest, // fieldValue if (varName.startsWith("field")) { continue; } String varValueEscaped = escapeJavascript(varValue); if (Var.JSTYPE_INT.equalsIgnoreCase(jsType)) { results.append("this." + varName + "=" + varValueEscaped + "; "); } else if (Var.JSTYPE_REGEXP.equalsIgnoreCase(jsType)) { results.append("this." + varName + "=/" + varValueEscaped + "/; "); } else if (Var.JSTYPE_STRING.equalsIgnoreCase(jsType)) { results.append("this." + varName + "='" + varValueEscaped + "'; "); // So everyone using the latest format doesn't need to // change their xml files immediately. } else if ("mask".equalsIgnoreCase(varName)) { results.append("this." + varName + "=/" + varValueEscaped + "/; "); } else { results.append("this." + varName + "='" + varValueEscaped + "'; "); } } results.append(" return this[varName];\"));\n"); } results.append(" } \n\n"); } return results.toString(); }
From source file:org.hyperic.hq.ui.validator.IdenticalValidator.java
/** * Validates if two fields are equal in terms of String's equal() * function./* w w w .j a v a 2s . c o m*/ * * Example of use: *<code> * <field property="password" depends="identical"> * <arg0 key="password.displayName"/> * <arg1 key="passwordConfirm.displayName"/> * <var> * <var-name>secondProperty</var-name> * <var-value>password2</var-value> * </var> * </field> * *</code> * * @return Returns true if the fields property and property2 are * identical. */ public boolean validate(Object bean, ValidatorAction va, Field field, ActionMessages msgs, HttpServletRequest request) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); String sProperty2 = field.getVarValue("secondProperty"); String value2 = ValidatorUtils.getValueAsString(bean, sProperty2); if (GenericValidator.isBlankOrNull(value)) { if (GenericValidator.isBlankOrNull(value2)) { return true; } return false; } if (!value.equals(value2)) { ActionMessage msg = Resources.getActionMessage(request, va, field); msgs.add(field.getKey(), msg); return false; } return true; }
From source file:org.hyperic.util.validator.common.CommonValidatorUtil.java
/** * Conditional validation method./* www . j a v a 2 s .c om*/ * @param bean to be tested * @param bean's field to be tested. * @param current validator * @return true if condition satisfied, false otherwise. */ public static boolean validateRequiredIf(Object bean, Field field, Validator validator) { Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null; boolean required = false; if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } int i = 0; String fieldJoin = "AND"; if (!GenericValidator.isBlankOrNull(field.getVarValue("field-join"))) { fieldJoin = field.getVarValue("field-join"); } if (fieldJoin.equalsIgnoreCase("AND")) { required = true; } while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) { String dependProp = field.getVarValue("field[" + i + "]"); String dependTest = field.getVarValue("field-test[" + i + "]"); String dependTestValue = field.getVarValue("field-value[" + i + "]"); String dependIndexed = field.getVarValue("field-indexed[" + i + "]"); if (dependIndexed == null) dependIndexed = "false"; String dependVal = null; boolean this_required = false; if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) { String key = field.getKey(); if ((key.indexOf("[") > -1) && (key.indexOf("]") > -1)) { String ind = key.substring(0, key.indexOf(".") + 1); dependProp = ind + dependProp; } } dependVal = ValidatorUtils.getValueAsString(form, dependProp); if (dependTest.equals(FIELD_TEST_NULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = false; } else { this_required = true; } } if (dependTest.equals(FIELD_TEST_NOTNULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = true; } else { this_required = false; } } if (dependTest.equals(FIELD_TEST_EQUAL)) { this_required = dependTestValue.equalsIgnoreCase(dependVal); } if (fieldJoin.equalsIgnoreCase("AND")) { required = required && this_required; } else { required = required || this_required; } i++; } if (required) { if ((value != null) && (value.length() > 0)) { return true; } else { return false; } } return true; }
From source file:org.jresearch.gossip.validator.Validator.java
/** * DOCUMENT ME!/*from w w w. jav a2s.co m*/ * * @param bean * DOCUMENT ME! * @param va * DOCUMENT ME! * @param field * DOCUMENT ME! * @param errors * DOCUMENT ME! * @param request * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean validateEmail(Object bean, ValidatorAction va, Field field, ActionMessages errors, HttpServletRequest request) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); Perl5Util util = new Perl5Util(); if (!GenericValidator.isBlankOrNull(value)) { if ((!util.match("/( )|(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)|(^_+@)|(^\\-+@)/", value)) && util.match( "/^[\\w\\'\\.\\-]+@((\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)|[a-zA-Z0-9\\-]{2,})$/", value)) { return true; } else { errors.add(field.getKey(), Resources.getActionMessage(request, va, field)); return false; } } return true; }
From source file:org.jresearch.gossip.validator.Validator.java
/** * DOCUMENT ME!//from w w w. j av a2 s .c om * * @param bean * DOCUMENT ME! * @param va * DOCUMENT ME! * @param field * DOCUMENT ME! * @param errors * DOCUMENT ME! * @param request * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean validateTwoFields(Object bean, ValidatorAction va, Field field, ActionMessages errors, HttpServletRequest request) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); String sProperty2 = field.getVarValue("secondProperty"); String value2 = ValidatorUtils.getValueAsString(bean, sProperty2); if (!GenericValidator.isBlankOrNull(value)) { try { if (!value.equals(value2)) { errors.add(field.getKey(), Resources.getActionMessage(request, va, field)); return false; } } catch (Exception e) { errors.add(field.getKey(), Resources.getActionMessage(request, va, field)); return false; } } return true; }