I am trying to generalize form fields for a form. I want to have different parsley.js
validation requirements. There are 2 non-standard attributes that I want to dynamically append to the input field: required
and data-parsley-range
. An example of a simple html without thymeleaf would be:
<input type=text required data-parsley-range=[1,100] />
I've tried the following with thymeleaf:
<input class="form-control" fieldType="text" th:attr="required=${field.isRequired ? 'required' : null}"
th:attr="data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}"/>
But I've got an error that th:attr
is defined multiple times.
So my question is: How can I define multiple attributes with help of th:attr
in a single html element?
My additional question is: How can I conditionally place the attributes? For example I don't want to write required='required'
at all if I can avoid it, same applies to the range.
The straight solution is to use a comma ,
to separate multiple attributes.
<input th:attr="required=${field.isRequired ? 'required' : null}, data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}" />
Alternatively, if you want to keep attributes separately for better reading purposes, you can use th:attrappend
:
<input th:attr="required=${field.isRequired ? 'required' : null}"
th:attrappend="data-parsley-range=${field.validStringLengthMin ? [${field.validStringLengthMin},${field.validStringLengthMax}] : null}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With