我建立了习俗验证属性。
[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
tring FormatErrorMessage(string name) { 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>
我没有任何验证参数,也没有打字笔字。
服务器侧验证完全可行,但客户方不可行。
任何想法?
这一观点
@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>
}