You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by "Raible, Matt" <Ma...@cable.comcast.com> on 2003/02/26 00:19:53 UTC
[proposal] Add Validating Two Fields to Validator (code
included)
I would like to propose that we add the validateTwoFields functionality to
the validator. I don't have the source, so I can't submit a "true" patch,
but hopefully this e-mail will get the ball rolling.
Add this method, in my case it's in org.appfuse.webapp.util.ValidationUtil:
public static boolean validateTwoFields(Object bean, ValidatorAction
va,
Field field, ActionErrors errors,
HttpServletRequest request) {
String value =
ValidatorUtil.getValueAsString(bean,
field.getProperty());
String sProperty2 = field.getVarValue("secondProperty");
String value2 = ValidatorUtil.getValueAsString(bean,
sProperty2);
if (!GenericValidator.isBlankOrNull(value)) {
try {
if (!value.equals(value2)) {
errors.add(field.getKey(),
Resources.getActionError(request, va, field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(),
Resources.getActionError(request, va, field));
return false;
}
}
return true;
}
Then in validation-rules.xml - add the following for server-side AND
client-side validation:
<validator name="twofields"
classname="org.appfuse.webapp.util.ValidationUtil"
method="validateTwoFields"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
depends="required"
msg="errors.twofields">
<javascript><![CDATA[
function validateTwoFields(form) {
var bValid = true;
var focusField = null;
var i = 0;
var fields = new Array();
oTwoFields = new twofields();
for (x in oTwoFields) {
var field = form[oTwoFields[x][0]];
var secondField =
form[oTwoFields[x][2]("secondProperty")];
if (field.type == 'text' ||
field.type == 'textarea' ||
field.type == 'select-one' ||
field.type == 'radio' ||
field.type == 'password') {
var value;
var secondValue;
// get field's value
if (field.type ==
"select-one") {
var si =
field.selectedIndex;
value =
field.options[si].value;
secondValue =
secondField.options[si].value;
} else {
value = field.value;
secondValue =
secondField.value;
}
if (value != secondValue) {
if (i == 0) {
focusField = field;
}
fields[i++] = oTwoFields[x][1];
bValid = false;
}
}
}
if (fields.length > 0) {
focusField.focus();
alert(fields.join('\n'));
}
return bValid;
}]]>
</javascript>
</validator>
I haven't "thouroughly" tested this, but it's working for me on a
password/confirm password scenario.
Thanks,
Matt
---------------------------------------------------------------------
To unsubscribe, e-mail: struts-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: struts-dev-help@jakarta.apache.org