...
Update the two fields of the Login page:
Code Block | ||
---|---|---|
| ||
@Persist @Property @Validate("required") private String userName; @Property @Validate("required") private String password; |
Now, rebuild the app, refresh the browser, and just hit enter:
The form has updated, in place, to present the errors. You will not be able to submit the form until some value is provided for each field.
Server Side Validation
Some validation can't, or shouldn't, be done on the client side. How do we know if the password is correct? Short of downloading all users and passwords to the client, we really need to do the validation on the server.
In fact, all client-side validation (via the validate parameter, or @Validate annotation) is performed again on the server.
It is also possible to perform extra validation there.
Code Block | ||
---|---|---|
| ||
/**
* Do the cross-field validation
*/
void onValidateFromLoginForm() {
if (!authenticator.isValid(userName, password)) {
// record an error, and thereby prevent Tapestry from emitting a "success" event
loginForm.recordError(passwordField, "Invalid user name or password.");
}
}
|
This is the validate event handler from the loginForm component. It is invoked once all the components have had a chance to read values out of the request, do their own validations, and update the properties they are bound to.
In this case, the authenticator is used to decide if the userName and password is valid. In a real application, this would be where a database or other external service was consulted.
If the combination is not valid, then the password field is marked as in error. The form is used to record an error, about a component (the passwordField) with an error message.
Entering any two values into the form and submitting will cause a round trip; the form will re-render to present the error to the user:
Notice that the cursor is placed directly into the password field.
Note |
---|
In versions of Tapestry prior to 5.4, a form with validation errors would result in a redirect response to the client; often, temporary server-side data (such as the userName field) would be lost. Starting in 5.4, submitting a form with validation errors results in the new page being rendered in the same request as the form submission. |
Customizing Validation Messages
...