Spring MVC - How to set the parent div class when there are validation errors?

Is it possible to associate an arbitrary css element class with a binding state model?

<form:form method="post" commandName="authForm" action="authenticate">
  <div id="login-error" class="control-group">
    <label>Login</label>
    <form:input path="name" />
    <span class="help-inline"><form:errors path="name" /></span>
  </div>

  <div class="control-group">
    <label>Password</label>
    <form:input path="password" />
    <span class="help-inline"><form:errors path="password" /></span>
  </div>

  <input type="submit" />
</form:form>

In this piece of code, I need to manage the class login-erroruntil control-groupwhen there are no errors and control-group errorwhen there is (the same idea for the second control-group).

What is the general solution here?

Update

Here is what I need when there is no binding error:

<div class="control-group"> <!-- !!!!!!!!!!!! -->
  <label>Login</label>
  <form:input path="name" />
  <span class="help-inline"><form:errors path="name" /></span>
</div>

Here is what I need when there is a binding error:

<div class="control-group error"> <!-- !!!!!!!!!!!! -->
  <label>Login</label>
  <form:input path="name" />
  <span class="help-inline"><form:errors path="name" /></span>
</div>

Looking for a solution.

+5
source share
3 answers

Here is a solution that works, but I'm not sure if this is really a good idea:

<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>
...
<form:form method="post" commandName="authForm" action="authenticate">
  <spring:bind path="name">
    <div class="control-group <%= status.isError() ? "error" : "" %>"
      <label>Login</label>
      <form:input path="name" />
      <form:errors path="name" cssClass="help-inline" />
    </div>    
  </spring:bind>
  ...
</form:form>
+8
source

I had the same problem and decided to use jQuery to solve it.

<div class="control-group">
    <form:label path="groupCode" cssClass="control-label"><spring:message code="lookUp.groupCode"/></form:label>
    <div class="controls">
        <form:input path="groupCode"/>
        <form:errors path="groupCode">
            <form:errors path="groupCode" cssClass="help-inline"/>
            <script type="text/javascript">
                $("#groupCode").parent().parent().addClass("error");
            </script>
        </form:errors>
    </div>
</div>
+2
source

I cannot find the right solution here. But you can go with JavaScript and try to find out if there is a range displayed in the view with the identifier "name" or not, and based on this condition you can achieve what you want.

Because when there is no binding error for the specified , it will not generate a span tag for it. And if there is an error for "name", then it will generate the corresponding span tag with its identifier.

Hope this helps you. Cheeers.

0
source

All Articles