开发者

Sending an alert after input validation without reloading page

I am validating the input of a form using grails validation for domain classes. I can differenciate between valid and invalid inputs, but the problem i cant get solved is that i wa开发者_StackOverflow中文版nt to show the missing/invalid inputs at the page without reloading it.

I wanted to use submitToRemote as shown in the example:

<g:form action="show">
        Login: <input name="login" type="text"></input>
        <g:submitToRemote update="updateMe" />
</g:form>
<div id="updateMe">this div is updated by the form</div>

Not sure if this really is the way i should go, any suggestions?


You could use submitToRemote element's before parameter to call a Javascript method which performs validation (and updates the page with any errors) asynchronously. I think that method would need to return false if there were any errors, otherwise return true.


You could attach an action in javascript, looking something like this (if you'd use jQuery):

$('#id_of_form').submit(function() {

   var login = $('input[name="login"]').val()
   if(login.length == 0) {
         // Show some error, about an empty login
         $('#updateMe').text('Empty login is not allowed')
         return false; // will prevent submitting the form
   }

   return true; // Will allow submitting the form 
})

Untested, but should work.


We move all the form to template and re-render it completely in Ajax, like:

_myForm.gsp:

<div id="userForm">

<!-- You can even add error list: -->
<g:hasErrors bean="${user}">
    <div class="errors">
      <grid:renderErrors bean="${user}"/>
    </div>
</g:hasErrors>

<g:form action="ajaxLogin">
        Login: <g:textField name="login" type="text" value="${user.login}"
          class="${hasErrors(bean: user, field: 'login', 'errors')}" />
        <g:submitToRemote update="userForm" />
</g:form>
</div>

controller:

def ajaxLogin = {
    User user = new User(params)
    if (!user.save()) {
        // validation errors get rendered here
        render template: 'myForm', model: [user : user]
    } else {
        render template: 'nextStep', model: [user : user, whatever: whatever]
    }
}

User has the impression that the form remained the same.

Though, for user login, I'd recommend that you use SpringSecurity plugin and not repeat it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜