Was wondering why the constraints created for a form are not included in the input tag directly when created through the form helper?
Explanation (using Play 2.1):
Model:
public class Account {
@MaxLength(5)
private String id = "";
... ...
view:
@form(action = routes.Application.addAccount()) {
@inputText(accountForm("id"), '_label -> "Enter your id:")
}
renders automatically in html as:
Should it not render like this (actually constraining the form text field):
How can I get code that will automatically include constraints such as these in the form? It's just that I do not really think it is a good idea to have a maxlength defined in the form model and a separate one defined in the view.
Thanks
If I've understood you correctly, it sounds like you're looking to implement one of these features:
Play's HTML templating engine doesn't natively provide this kind of client-side instant form validation. This functionality needs to be implemented via JavaScript, and JavaScript generation is not really a concern for Play.
If you want to progressively enhance your form and provide client-side validation, you'll have to write the JavaScript yourself. Of course there are libraries that you can use to help you with this task. For example, if you are already using jQuery you can use its validation plugin.
As you've mentioned in your question, it would be better to have a maximum length limit declared in one place only, rather than duplicated in your client-side JavaScript code and your server-side Java code. As a suggestion, you could keep the limit declared in Java code, but introduce a new action in your controller tier that returns a JSON response containing this limit. This action could then be called via AJAX when loading your form page.
EDIT
Didn't know about the
maxlength
attribute, thanks Saad. If you feed in your maximum length limit as an input parameter to your template, you can populate aninput
element'smaxlength
attribute as follows:There may be a more elegant way to pass
maxLength
into your HTML template (e.g use the HTTP context map, or have it as a public field on yourAccount
form object). The above code snippet just demonstrates how to correctly generate the input text field once you can access it in the template.