我用 Durandal/Breeze/Knockout 开发了一个项目。现在,我需要使用正则表达式验证视图上的输入字段。
我的第一次尝试是在我的实体框架模型上插入数据注释服务器端,如下所示:
public class Transport
{
[Key]
public int Id { get; set; }
[Required, RegularExpression(@"^\d{2}\.\d{3}$")]
public string AffairNumber { get; set; }
...
然后在客户端,我有一个解析这些注释并插入验证的函数,如下所示:
var addValidationRules = function(entity) {
var entityType = entity.entityType;
if (entityType) {
for (var i = 0; i < entityType.dataProperties.length; i++) {
var property = entityType.dataProperties[i];
var propertyName = property.name;
var propertyObject = entity[propertyName];
var validators = [];
for (var u = 0; u < property.validators.length; u++) {
var validator = property.validators[u];
var nValidator = {
propertyName: propertyName,
validator: function (val, other) {
var error = this.innerValidator.validate(val, { displayName: this.propertyName });
this.message = error ? error.errorMessage : "";
return error === null;
},
message: "",
innerValidator: validator
};
validators.push(nValidator);
}
propertyObject.extend({
validation: validators
});
}
for (var i = 0; i < entityType.foreignKeyProperties.length; i++) {
var property = entityType.foreignKeyProperties[i];
var propertyName = property.name;
var propertyObject = entity[propertyName];
var validators = [];
for (var u = 0; u < property.validators.length; u++) {
var validator = property.validators[u];
var nValidator = {
propertyName: propertyName,
validator: function (val, other) {
var error = this.innerValidator.validate(val, { displayName: this.propertyName });
this.message = error ? error.errorMessage : "";
return error === null;
},
message: "",
innerValidator: validator
};
validators.push(nValidator);
}
propertyObject.extend({
validation: validators
});
if (!property.isNullable) {
//Bussiness Rule: 0 is not allowed for required foreign keys
propertyObject.extend({ notEqual: 0 });
}
}
}
log('Validation rules added', entity, false);
};
为我想验证的每个实体调用此函数,如下所示:
function transportInitializer(transport) {
addValidationRules(transport);
};
此解决方案仅适用于基本验证,Required
但对于正则表达式验证它不起作用。
我的实际解决方案是用这样的模式“扩展”我的可观察属性affairNumber
:
transport.affairNumber.extend({
pattern: {
message: 'The affair number must be correctly formatted',
params: '^\\d{2}\\.\\d{3}$'
}
});
因此,当在我的输入中输入不正确的值时,验证失败。我对这个解决方案非常满意,因为我更喜欢在我的实体框架模型(服务器端)上设置验证,而不是在客户端重复验证。
我的问题:Breeze 是否允许我验证从服务器端检索到的正则表达式?还有另一个我忽略的选项吗?
谢谢。