【发布时间】:2014-07-01 13:18:53
【问题描述】:
我有模型课:
[FluentValidation.Attributes.Validator(typeof(CrcValidator))]
public class CrcModel
{
[Display(Name = "Binary value")]
public string binaryValue { get; set; }
[Display(Name = "Generator")]
public string generator { get; set; }
}
和带有谓词的验证器类:
public class CrcValidator : AbstractValidator<CrcModel>
{
public CrcValidator()
{
RuleFor(x => x.binaryValue)
.NotEmpty().WithMessage("Binary value is required")
.Matches(@"(0|1)*").WithMessage("This value is not valid binary value");
RuleFor(x => x.generator)
.NotEmpty().WithMessage("Generator is required")
.Matches(@"(0|1)*").WithMessage("Generator must be valid binary value")
.Must(CompareLength).WithMessage("Length must be lesser than length of binary value - 1");
}
private bool CompareLength(CrcModel model, string value)
{
return model.binaryValue.Length - 1 > model.generator.Length;
}
}
我在 CompareLength 函数中放置了断点,并且从表单中正确读取了每个值。问题是我的表单通过了验证,即使我的谓词函数返回 false。 NotEmpty 和 Matches 规则工作得很好,只有 Must 似乎被省略了。
编辑
提交按钮的jQuery(“按钮”类型):
$(function () {
$("#Button1").click(function () {
var form = $("#Form1");
if ($(form).valid()) {
$.ajax({
type: 'POST',
url: 'Compute',
data: $(form).serialize(),
success: function (result) {
$("#remainder").val(result.remainder);
$("#signal").val(result.signal);
}
});
}
});
});
控制器动作处理表单提交:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Compute([Bind(Include = "binaryValue,generator")] CrcModel model)
{
if (ModelState.IsValid)
{
model.remainder = ComputeFrame(model.binaryValue, model.generator);
model.signal = model.binaryValue + model.remainder;
}
return Json(new { remainder = model.remainder, signal = model.signal });
}
来自 Must 规则的验证在服务器端有效,但消息不显示。
【问题讨论】:
标签: c# jquery ajax asp.net-mvc-5 fluentvalidation