1

I have a "Create an account" form that is handled by spring. I am using jquery to auto-update some of the fields.

    <script type="text/javascript">
    $().ready(

             function() {

                 $("#item1").keyup(function() {
                     var text= (this).value;
                     //modify text
                     $("#item4").val(text);

                    });


             });
    </script>

     <form:form action="${form_url}" method="POST" modelAttribute="object" enctype="${enctype}">
     <label for="Item1">Item1:</label>
     <input type="text" id="item1" name="item_1"/>
     <br></br>
     <br></br>
     <label for="Item2">Item2:</label>
     <input type="text" id="item2" name="item_2"/>
     <br></br>
     <br></br>
     <label for="Item3">Item3:</label>
     <input type="text" id="item3" name="item_3"/>
     <br></br>
     <br></br>
     <label for="Item4">Item4:</label>
     <input type="text" id="item4" name="item_4"/>
    </form:create>

<input id="proceed" type="submit" value="Save"/>

Upon pressing the submit button I need to make sure the first field "item1" is not empty. I haven't found a solution to this uses spring forms. Thanks in advance!

1

1 Answer 1

1

There are many ways to implement such validation. It is recommended you do both client and server side.

For client side you can simple create a click listener to the submit button

$('.submitbutton').click(function(e) {
  e.preventDefault();
  if($('#item1').val().trim() != '') $('.myform').submit()
  else { $('.item1_error').show();
}

Or (even better) use 3rd party validation library

For the server side you can use hibernate-validator and add @NotEmpty annotation to your form bean

public class MyForm {

  @NotEmpty private String item1;

  // ...

}

Then on your controller handler method just decorate the parameter with @Valid. Any errors can be checked through the BindingResult object

@RequestMapping(..)
public String myhandler(@Valid @ModelAttribute("object") MyForm myForm, BindingResult binding) {
  if(binding.hasErrors()) {
    // ...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.