You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/WebMVC/wwwroot/test.html

100 lines
3.4 KiB

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
var validator = {
errors: [],
valid: function (schema, model) {
this.errors = [];
var list = [];
for (var propName in schema.properties) {
var prop = schema.properties[propName];
for (var ruleIndex in prop.rules) {
var rule = prop.rules[ruleIndex];
list.push(this[rule.name](model, propName, rule));
}
}
return Promise.all(list);
},
validInternal: function (schema, model, propName) {
var list = [];
var prop = schema.properties[propName];
for (var ruleIndex in prop.rules) {
var rule = prop.rules[ruleIndex];
list.push(this[rule.name](model, propName, rule));
}
return Promise.all(list);
},
addError: function (propName, name, message) {
var prop = this.errors.find(o => o.name === propName);
if (!prop) {
prop = { name: propName, errors: [] };
this.errors.push(prop);
}
var error = prop.errors.find(o => o.name === name);
if (!error) {
error = { name: name };
prop.errors.push(error);
}
error.message = message;
},
removeError: function (propName, name) {
var propIndex = this.errors.findIndex(o => o.name === propName);
if (propIndex > -1) {
var prop = this.errors[propIndex];
var errorIndex = prop.errors.findIndex(o => o.name === name);
if (errorIndex > -1) {
prop.errors.splice(errorIndex, 1);
if (prop.errors.length === 0) {
this.errors.splice(propIndex, 1);
}
}
}
},
required: function (model, propName, rule) {
var result = model[propName] ? true : false;
if (result) {
this.removeError(propName, rule.name, rule.message);
}
else {
this.addError(propName, rule.name);
}
return Promise.resolve(result);
}
};
var schema = {
type: 'object',
title: '对象',
properties: {
name: {
title: '名称',
rules: [
{
name: 'required',
message: '必填项'
}
]
}
}
};
var model = {
name: null
};
function valid() {
validator.valid(schema, model).then(function (value) {
alert(validator.errors.length);
model.name = 1;
}).then(function (value) {
validator.valid(schema, model).then(function (value) {
alert(validator.errors.length);
});
});
}
valid();
</script>
</body>
</html>