在视图中,我为视图模型创建了一个表单。我已经使用Twitter Bootstrap向导插件将表单分为多个部分。用户可以通过单击“下一步”按钮访问下一部分。每个部分都有为该部分的模型属性定义的Fluent Validation RuleSet。我在每个RuleSet中定义的规则都与Fluent Validaiton的客户端验证兼容。
单击下一步按钮时,最好的方法是:
我已经读过Fluent Validation start guide和这个question。尽管他们演示了如何在服务器端实现我想要的功能,但他们没有似乎来解决我的客户端问题。我加粗“似乎”是因为我对Fluent Validation和MVC相当陌生,因此,我可能误解了链接的内容。
答案 0 :(得分:1)
您可以使用来自Fluent Validation使用的jQuery验证库中的命令。
在表单的元素中,定义一个有助于您识别验证组的属性。例如
@Html.EditorFor(model => model.GroupA_TextA, new { htmlAttributes = new { @class = "form-control", data_validation_group = "GroupA" }})
使用jQuery验证库中的.settings.ignore
语法来控制要验证的组。
我创建了一个类,该类提供了用于验证Fluent Validation验证表单中的组以及整个表单的功能。我在下面包括了TypeScript和已转译的JavaScript。
TypeScript
/**
* For validating a form when Fluent Validation is used for model valdiation.
*/
interface IFluentValidationFormValidator {
/**
* The form to validate.
*/
form: JQuery<HTMLElement>;
/**
* The name of the validation group to validate.
*/
group: string;
/**
* Validate the entire form.
*/
validate(): boolean;
/**
* Validate a validation group in the form.
* @param group The name of the validation group to validate.
*/
validateGroup(): boolean;
}
/**
*
*/
class StandardFluentValidationFormValidator implements IFluentValidationFormValidator {
/**
* @inheritdoc
*/
form: JQuery<HTMLElement>;
/**
* @inheritdoc
*/
group: string;
/**
* @inheritdoc
*/
validate(): boolean {
const formValidator = this.form.validate();
formValidator.form();
return formValidator.valid();
}
/**
* @inheritdoc
*/
validateGroup(): boolean {
// The form validator.
const formValidator = this.form.validate();
// Perform standard validation on form if the validation group is undefined.
if (this.group === undefined) {
formValidator.form();
return formValidator.valid();
}
// Current group validation settings.
const initialValidateIgnoreSetting = formValidator.settings.ignore;
// Ignore all elements but the group.
formValidator.settings.ignore += `,:not([data-validation-group=${this.group}])`;
// Valdiate the form.
formValidator.form();
// Reset group validation settings.
formValidator.settings.ignore = initialValidateIgnoreSetting;
// Return the validation state.
return formValidator.valid();
}
}
JavaScript
"use strict";
var StandardFluentValidationFormValidator = (function () {
function StandardFluentValidationFormValidator() {
}
StandardFluentValidationFormValidator.prototype.validate = function () {
var formValidator = this.form.validate();
formValidator.form();
return formValidator.valid();
};
StandardFluentValidationFormValidator.prototype.validateGroup = function () {
var formValidator = this.form.validate();
if (this.group === undefined) {
formValidator.form();
return formValidator.valid();
}
var initialValidateIgnoreSetting = formValidator.settings.ignore;
formValidator.settings.ignore += ",:not([data-validation-group=" + this.group + "])";
formValidator.form();
formValidator.settings.ignore = initialValidateIgnoreSetting;
return formValidator.valid();
};
return StandardFluentValidationFormValidator;
}());