2012-03-14 156 views
0

在我的mvc 3应用程序中,我想在用户试图提交表单时执行一个函数。在该功能中,我将检查多个字段以确定用户在提交之前是否提供了必要的数据。MVC自定义客户端验证

如何在用户尝试提交表单时连接脚本以执行操作?

(自定义验证函数中,我需要检查,如果各项复选框被选中,如果是的话,额外的值从dropdownlists等选择)

回答

5

我怎么能联播当用户试图提交表单被执行的脚本?

你可以订阅.submit事件的形式,并呼吁标准的客户端验证后调用自定义函数:

$(function() { 
    $('form').submit(function() { 
     if (!$(this).valid()) { 
      // standard client validation failed => prevent submission 
      return false; 
     } 

     // at this stage client validation has passed. Here you could call your 
     // function and return true/false depending on the result of your 
     // custom function 
    }); 
}); 

另一种可能性是编写自定义验证属性和挂钩自定义适配器如this answersimilar one所示。

+0

丹吉特,打我到20秒! – Martin 2012-03-14 12:29:39

0

在视图(剃刀或Java),你会在html中定义一个脚本,并在那里进行客户端验证。

例如:

<script> 
    //define your script here, ie. $.(#tagtovaildate).validate(); 
</script> 

<html> 
    //code 
</html> 
2
$('#formId').submit(function() { 
    var standardIsValid = $(this).validate().form(); 
    var customIsValid = customValidations(); 
    if (!standardIsValid || !customIsValid) { 
     return false; 
    } 
});