简体   繁体   中英

How can I use a translator and/or validator to make a String field required in Tapestry 4?

I'm using Tapestry 4.

I have several TextFields whose values get passed into Strings in the page class, and they work great as long as there is some content in the fields. Most of them are optional, so I believe I can use the StringTranslator with empty= in that case, but for a couple of fields for which a value is required, I'm having a hard time getting validation to work.

I expected a simple required validator to work:

<component id="myRequiredField" type="TextField">
    <binding name="value" value="ognl:stringValue" />
    <binding name="validators" value="validators:required" />
</component>

Failing that, I expected minLength to work:

<component id="myRequiredField" type="TextField">
    <binding name="value" value="ognl:stringValue" />
    <binding name="validators" value="validators:required,minLength=1" />
</component>

Both attempts at validation allow the value as retrieved with getStringValue() to be null upon form submission. My Form and Submit components look like:

<component id="myUpdateForm" type="Form">
    <binding name="delegate" value="beans.validationDelegate" />
</component>
<component id="submitUpdate" type="Submit">
    <binding name="action" value="listener:doUpdate" />
</component>

It turns out that the validation was working, but I wasn't checking whether my validation delegate had errors before operating on the incoming data. The following seems to be the correct approach to take in any listener that depends on validation, given the setup as listed in the question:

@Bean
public abstract ValidationDelegate getValidationDelegate();

public void doUpdate() {    
    if (!getValidationDelegate().getHasErrors()) {
        // business logic
    }
}

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