Search code examples
grailsgrails-orm

Grails form validation on client


I have the following domain class and gsp and can't seemed to work for validation on client gsp side.

The domain class:

class User {
   String username
   String password
   String emailAddress
   static hasMany = [memberships: Membership]
}

The form gsp:

<div class="error-details">
   <g:hasErrors bean="${user}">
       <ul>
           <g:eachError var="err" bean="${user}">
              <li>${err}</li>
           </g:eachError>
       </ul>
   </g:hasErrors>
</div>
<form action="${raw(createLink(controller:'purchase', action: 
'createSubscription'))}" method="POST">
   <input type="text" name="username">
   <input type="text" name="password">
   <input type="text" name="emailAddress">
</form>

Is there anything I've missed out?


Solution

  • You should use the built in Taglibs for rendering fields. Don't use standard HTML. This way you allow Grails to determine the constraints based on your domain class.

    You didn't specify the version of grails you're running:

    The latest version 3.3.x uses the fields plugin, please see https://grails-fields-plugin.github.io/grails-fields/latest/ref/Tags/field.html

    <f:field bean="user" property="username"/>
    <f:field bean="user" property="password" />
    <f:field bean="user" property="emailAddress"/>
    

    or just use this

    <f:all bean="user"/>
    

    Which will render all the attributes of user.

    Make sure you update your domain and include the following constraint

    static constraints = {
         password password: true
    }
    

    Additional constraints are possible. Please see https://docs.grails.org/latest/ref/Constraints/Usage.html

    In older version of grails, please see https://grails.github.io/grails2-doc/2.4.3/ref/Tags/field.html

    <g:field type="text" name="username" value="${userInstance?.username}"/>
    <g:field type="password" name="password" value="${userInstance?.password}"/>
    <g:field type="text" name="username" value="${userInstance?.username}"/>