【问题标题】:How to display a server side validation error on view page如何在视图页面上显示服务器端验证错误
【发布时间】:2012-11-30 12:27:32
【问题描述】:

因为我正在使用 grails 框架但不使用控制器。我的应用程序是“单页应用程序”。我不想重新加载我的页面,所以我已经编写了服务,即带有 Ajax 调用的 RegistrationService。所以我使用淘汰赛进行数据绑定。数据库使用的是 postgresql 。 我有一个查看页面,其中有一个电子邮件字段。当我输入重复的电子邮件 ID 并单击保存按钮时,我会看到一个验证错误,即“电子邮件已被占用”但即使我正在编写一个唯一的 ID,我也会收到相同的验证错误。这是因为它在 modalModal.js 页面中处于错误状态,所以我不知道如何解决这个问题。我只想在输入唯一 ID 并单击保存按钮时,它不应该给出验证错误。

_newCostingpage.gsp  (my view page)

    <div id="light" class="white_content" style="color: black;">
    <form action="#/cart" method="post">
    <input type="hidden" name="url" value="${grailsApplication.config.serverURL}"/>
    <p><label>first name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="firstName"
             class="formElement" data-bind='value: firstName'/></label></p>
    <p><label>last name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="lastName" 
              class="formElement" data-bind='value: lastName' /></label></p>
    <p><label>organisation: <input name="organisation" class="formElement" data-
              bind='value: organisation' /></label></p>
<p><label>email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <input name="email" class="formElement" data-bind='value: email' /></label><label 
         id="errorDiv"></label></p>
<p><label>password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="password" name="password"
         class="formElement" data-bind='value: password' /></label></p>
 <p><label style="margin-left: -37px;">confirm password:</label> <input
        type="password" name="confirmPassword" class="formElement" data-bind='value:
        confirmPassword' /></p>
 <p><input type="submit" value="register"/></p>
</form>
 <a href="javascript:void(0)"onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';clearBox();">Close</a>
        </div>
        <div id="fade" class="black_overlay"></div>
    </div>

Domain class :-\

  class Registration {
String firstName
String lastName
String organization
String email
String password
String confirmPassword

static constraints = {
    firstName(nullable:false)
    lastName(nullable:true)
    organization(blank:false)
    email(nullable:false,email:true,unique:true)
    password(blank:false)
    confirmPassword(blank:false)
               }
            }

modalModal.js

var ratPack = $.sammy(function() {
this.post('#/cart', function() {
    var firstname = this.params['firstName'];
    var lastName = this.params['lastName'];
    var organisation = this.params['organisation'];
    var email = this.params['email'];
    var password = this.params['password'];
    var confirmPassword = this.params['confirmPassword'];
    var baseurl = this.params['url'];
    $.ajax({
        type : 'POST',
        url :'http://localhost:9191/guido-rest-
                          resource/api/registration/'+firstname+'/'+lastName+'/'+email,
        success : function() {
            alert("success:");
        },
        error:function(){
           $('#errorDiv').text("Email has already been taken");
        }
    });
    });
      });
        $(function() {
       ratPack.run();
        });
        function clearBox(){
       $('.formElement').val("");
       }


   RegistrationResource.groovy

         package common.rest.resourcepl
         import static org.grails.jaxrs.response.Responses.*
         import javax.ws.rs.Consumes
         import javax.ws.rs.GET
         import javax.ws.rs.Produces
         import javax.ws.rs.Path
       import javax.ws.rs.PathParam
       import javax.ws.rs.POST
      import javax.ws.rs.core.Response
      import common.servicepl.RegistrationService
     @Path('/api/registration')
       class RegistrationResource {
   @GET
   @Produces('text/plain')
   String getRegistrationRepresentation() {
    'Registration'
    }
   def registrationService;
    @POST
    @Path('/{firstname}/{lastName}/{email}')
    Response create(@PathParam('firstname') String firstname,
                @PathParam('lastName') String lastName,
                @PathParam('email') String email) {
                return  
        RegistrationService().createRegistration(firstname,lastName,email);
  }
     }

     RegistrationService.groovy

         package common.servicepl
         import common.persistencepl.Registration
         class RegistrationService {
              def createRegistration(String firstName,String lastName,String email) {
        println "Inside Registration Service"
        def reg = new Registration();
        reg.firstName = firstName;
        reg.lastName = lastName;
        reg.password = "asdf";
        reg.confirmPassword = "asdf";
        reg.email = email;
        reg.organization = "fasdf";
        if(reg.save([flush:true])){
           return true
        }
        else
        {
          return false
        }
          }
         }

【问题讨论】:

  • 当您从同一个应用程序调用服务时,不要像http://localhost...那样指定完整路径,请指定相对于您当前页面/api/registration...的完整路径

标签: ajax grails sammy.js


【解决方案1】:

服务器应在响应中包含服务器端错误。

使这些错误消息成为 viewmodal 的属性,并将其绑定到样式正确的 html 段。

另外,当您从同一个应用程序调用服务时,不要指定完整路径,如 http://localhost...,指定相对于您当前页面的完整路径 /api/registration...

【讨论】:

  • 如果您查看我的视图页面,我已经创建了一个 id="errorDiv"。使用了这个 id 并在 modalModal.js 中创建了一个错误属性
  • 您最好重新渲染表单服务器端并检查错误。查找&lt;g:hasErrors /&gt; 和&lt;g:renderErrors /&gt;
  • @JamesKleeh:谢谢回复。但是我想知道的是,通过请求我可以将我的数据值保存到数据库中,但是在响应的情况下,它不是属性。这就是为什么我进入 modalModal.js 的错误属性。但是为什么会发生这种情况以及为什么我没有将警报视为“成功”?
  • @BuddhiP :我正在从我的差异应用程序中调用服务。
  • @BuddhiP:如果我尝试在一个应用程序中调用该服务,那么我会得到我的答案,即成功。如果我有 servicein diff 应用程序那么它不工作?有什么可能的解决方案吗?
【解决方案2】:

在 grails 控制器中你应该写:

if (!beanName.hasErrors() && beanName.validate()) {
        // TODO 
   } else {
         render status: Constants.SC_VALIDATION_FAILED, view: "viewName", model: [beanName: beanName]
}

在视野中:

<div>
 <g:hasErrors bean="${beanName}">
   <div class="errors">
     <g:renderErrors bean="${beanName}" as="list"/>
   </div>
 </g:hasErrors>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多