简体   繁体   中英

Struts2 condition on validation

I have a form with 5 "name" fields which represent a String tab, example

obj.props[0].name
obj.props[1].name
obj.props[2].name
obj.props[3].name
obj.props[4].name

but these fields, if they are filled, must be different. So i made an xml validator. i tried something like that:

<validator type="expression">
    <param name="expression">!obj.props[0].name.equals(obj.props[1].name) || 
    !obj.props[0].name.equals(obj.props[2].name) || 
    !obj.props[0].name.equals(obj.props[3].name) || 
    !obj.props[0].name.equals(obj.props[4].name)...</param>
    <message key="create.obj.error.propsdiff" />
    </validator>

but it doesn't work. do you have any idea about how conditions are used in struts2 validation?

Try something like:

action class

@Override
public void validate() {

    List<String> list = new ArrayList<String>();

    // For : 
    //  i. Props[]     : obj.getProps()[i].getName()
    // ii. List<Props> : obj.getProps().get(i).getName()

    // 1. names is mandatory fields (with requiredstring validator)
    // foreach () {
    //      list.add(obj.getProps[i].getName().trim());
    // }

    // 2. names is non-mandatory fields
    // foreach () {
    //      String name = obj.getProps[i].getName().trim();
    //      if(!name.isEmpty())
    //          list.add(name);
    // }

    Set<String> set = new HashSet<String>(list);

    if (set.size() < list.size()) {
        addActionError(getText("create.obj.error.propsdiff"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM