ASP.NET MVC 3验证模糊

时间:2011-01-20 03:31:05

标签: jquery asp.net-mvc asp.net-mvc-3 jquery-validate

当文本框失去焦点时,如何调用验证?例如

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
}

public class RegisterViewModel
{
    [Required]
    [StringLength(5)]
    public string Name { get; set; }
}

此外,如何通过调用操作来检查名称是否已存在?

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

您可以使用setDefaults()覆盖onfocusout属性,并使用始终通过调用valid()方法评估模糊元素的函数来覆盖{{3}}属性。

// enable eager evaluation
$.validator.setDefaults({
    onfocusout: function (element) {
        $(element).valid();
    }
})

热切评估演示
(标签显示后需要显示)

&#13;
&#13;
// enable eager evaluation
$.validator.setDefaults({
  onfocusout: function (element) {
    $(element).valid();
  }
});

$("form").validate();
&#13;
input.error {
  border-color: red
}
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>

<form >
  <input type="text" name="Name" required /><br/>
  <input type="text" name="Email" required /><br/>
  <input type="submit" value="Submit"/>
</form>
&#13;
&#13;
&#13;

正常演示
(在提交之前不需要显示)

&#13;
&#13;
$("form").validate();
&#13;
input.error {
  border-color: red
}
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>

<form >
  <input type="text" name="Name" required /><br/>
  <input type="text" name="Email" required /><br/>
  <input type="submit" value="Submit"/>
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

远程验证是MVC 3的一项新功能:http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx