You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Dan Allen <da...@mojavelinux.com> on 2003/04/15 04:22:35 UTC
maxselected, for those interested
Here is the necessary code to get maxselected working for the
select-multiple element when validating. These means you can only
select x number of options from a multiple select. This can be
extended for other elements, but I have not gotten to that yet.
<validator
name="maxselected"
classname="net.creativerge.struts.validator.FieldChecks"
method="validateMaxSelected"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.maxselected">
<javascript><![CDATA[
function validateMaxSelected(form) {
var bValid = true;
var focusField = null;
var i = 0;
var fields = new Array();
oMaxSelected = new maxselected();
for (x in oMaxSelected) {
if (form[oMaxSelected[x][0]].type == 'select-multiple') {
var iMax = parseInt(oMaxSelected[x][2]("maxselected"));
var numSelected = 0;
for (var j = 0; j < form[oMaxSelected[x][0]].options.length; j++)
{
if (form[oMaxSelected[x][0]].options[j].selected)
{
numSelected++;
if (numSelected > iMax)
{
if (i == 0) {
focusField = form[oMaxSelected[x][0]];
}
fields[i++] = oMaxSelected[x][1];
bValid = false;
break;
}
}
}
}
}
if (fields.length > 0) {
focusField.focus();
alert(fields.join('\n'));
}
return bValid;
}]]>
</javascript>
</validator>
public static boolean validateMaxSelected(
Object bean,
ValidatorAction va,
Field field,
ActionErrors errors,
HttpServletRequest request)
{
try
{
String value[] = BeanUtils.getArrayProperty(bean, field.getProperty());
int max = Integer.parseInt(field.getVarValue("maxselected"));
if (value != null && value.length > max)
{
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;
}
Hope you find it useful.
Dan
--
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Daniel Allen, <da...@mojavelinux.com>
http://www.mojavelinux.com/
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'One Microsoft Way' is more than just an address.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
---------------------------------------------------------------------
To unsubscribe, e-mail: struts-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: struts-user-help@jakarta.apache.org