Page 1 of 1

Search box validation

Posted: Mon Sep 02, 2013 10:43 am
by hiteshsingla
Hi,

I am trying to show error message when user tries to search for blank string.

For this i have created three files Mysearchvalidator,Mysearchcontroller,Mysearchform

Mysearchvalidator look likes as follow

Code: Select all

public static void validate(String query, Errors errors) {
      if (query == null || query.length() == 0 ||query.contains("Please Enter your Text")) {
         
         errors.reject("q", "searchText.required");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "searchText", "searchText.required");
        }
      
    }


Searchcontroller extending mysearchcontroller

Mysearchcontroller look like following

Code: Select all

public String search3(Model model, HttpServletRequest request, HttpServletResponse response,String query,BindingResult errors) throws ServletException, IOException, ServiceException {
.
.
.
Mysearchvalidator.validate(query,errors);
       if (errors.hasErrors())
       {
          
          return searchView;
       }
.
.
.


and search controller look like this

Code: Select all

public String search(HttpServletRequest request, HttpServletResponse response,
          @RequestParam(required = false) String q,@ModelAttribute("searchForm") Mysearchform searchForm,BindingResult errors,Model model) throws ServletException, IOException, ServiceException {
       
        return search3(model, request,response, q ,errors);
    }


Header.html

Code: Select all

 <div id="search">
            <blc:form th:action="@{/search}" th:object="${searchForm}"  method="POST">
            <input type="search" class="search" name="q" th:value="${originalQuery}" />
              <span th:if="${#fields.hasErrors('searchText')}" th:errors="*{searchText}"></span>
              <input type="submit" id="search_button" value="go" />
            </blc:form>
        </div>


But I am getting following error

1.Exception evaluating SpringEL expression: "#fields.hasErrors('searchText')" (layout/partials/header:42)
2.java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchForm' available as request attribute

Thanks