我已创建自定义验证属性
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidateDublicateNameAttribute : ValidationAttribute, IClientValidatable
{
private const string _defaultErrorMessage = "Library with title {0} is already exist";
private UnitOfWork unit = new UnitOfWork();
public ValidateDublicateNameAttribute()
: base(_defaultErrorMessage)
{
}
public override s
使用FormatErrorMessage(字符串名称) { return String.Format(ErrorMessageString,name); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string valueAsString = value as string;
ValidationResult result = ValidationResult.Success;
if (String.IsNullOrEmpty(valueAsString))
{
if (unit.ResourceSrvc.GetLibraryByTitle(valueAsString) != null)
{
result = new ValidationResult(String.Format(_defaultErrorMessage,value));
}
}
else
{
result = new ValidationResult("Title cant be empty or null");
}
return result;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "dublicatename",
};
yield return rule;
}
}
并使用它装饰我的模型
public class ResourceLibraryModel
{
public Guid LibraryId { get; set; }
[Required]
[ValidateDublicateName(ErrorMessage="title cant dublicate")]
public string Title { get; set; }
}
在客户端我有
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod("dublicatename", function (value, element, params) {
alert("test");
});
});
</script>
我没有任何验证参数,也没有写$ .validator.unobtrusive.adapters.add(....)
服务器端验证工作正常,但客户端不起作用。
有什么想法吗?
这是视图
@using (Ajax.BeginForm("CreateLibrary", "Resource", new AjaxOptions { OnSuccess = "RequestSucceeded"}))
{
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div>
@*<div style="margin-bottom:15px">
<label><b>Library information:</b></label>
</div>*@
<div class="editor-field">
@Html.TextBoxFor(m => m.Title, new { @class = "logon-field" })
@Html.ValidationMessageFor(m => m.Title)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Title)
</div>
</div>
}
答案 0 :(得分:0)
我认为问题是必须在您的javascript代码后加载jquery.validate.min.js
...
答案 1 :(得分:0)
只是猜测但您是否在Web.config文件中启用了客户端验证?
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
如果是,请按照此链接中的启用客户端验证部分进行操作:http://www.asp.net/mvc/tutorials/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript