2012-02-05 69 views
0

我有一个验证器和2个按钮的形式,内部形状:排除按钮从验证

<input type="submit" class="LFL_btn" value="" /> 
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn" id="btnRegister" /> 

但验证工作和第二个按钮了。为什么以及如何解决它?

回答

0

为什么?

因为jquery.validate在您通过劫持此表单的提交事件来提交表单时发挥作用。而且由于这两个都是提交按钮,所以对它们都运行验证。

如何解决?

添加class="cancel"你想从验证,这将指示jQuery.validate插件不运行验证排除按钮:

<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" /> 
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" /> 

这已经涵盖了documentation

显然这一切都只涉及客户端验证。在服务器上,这是一个完全不同的故事。如果你想在点击某个按钮时禁用验证,你首先需要知道哪个按钮被点击。

<button type="submit" class="LFL_btn" name="validate" value="validate">Validate</button> 

,然后你的控制器动作检查中,如果这个按钮是用来提交表单和:这可以通过给第一按钮name属性,然后检查服务器上的该参数的值从请求发生仅在此情况下应用验证:

[HttpPost] 
public ActionResult Foo(string validate) 
{ 
    if (!string.IsNullOrEmpty(validate)) 
    { 
     // the Validate button was clicked: 
     var model = new MyViewModel(); 
     if (!TryUpdateModel(model)) 
     { 
      // there were validation errors => redisplay the view 
      return View(model); 
     } 
     // validation went fine => do some processing... 
    } 
    else 
    { 
     // the image button was clicked 
     // do some other processing ... 
    } 
} 
+0

奇怪,但不起作用... – John 2012-02-05 18:57:01