-
Notifications
You must be signed in to change notification settings - Fork 1
Implementing validation rules
Roberto Prevato edited this page Mar 10, 2016
·
12 revisions
To implement dynamic validation, define the validation as a function that returns validation rules.
/* dataentry schema */
schema: {
propertyOne: {
//This validation is dynamic
validation: function () {
//the function is called in the context of the scope (Angular); or model (Knockout); or form element (basic plugin usage)
var rules = [];
if (someCondition)
return ["required"];
//otherwise:
return ["none"];
}
},
propertyTwo: {
//This validation is static
validation: ["required"]
}
}
To define a custom validation rule, the $.Forms.Validation.Rules object must be extended:
//custom rule definition: add a property to the $.Forms.Validation.Rules object
$.Forms.Validation.Rules.myCustomRule = {
fn: function (field, value, forced) {
if (!value) return true;//return true if the value is empty, because this validation rule is not checking if a required field is filled.
//return true if the value is composed by 3 digits, followed by an hyphen and then 2 letters
if (/\d{3}-[a-zA-Z]{2}/.test(value))
//value is valid
return true;
//value is not valid
return $.Forms.Validation.GetError(I.t("errors.invalidValue"), arguments);
}
};
The custom validation rule then can be used inside validation schemas:
schema: {
property: {
validation: ["myCustomRule"]
}
}
//custom rule definition: add a property to the $.Forms.Validation.Rules object
$.Forms.Validation.Rules.myAjaxRule = {
deferred: true, //validation rule is deferred
fn: function (field, value, forced) {
return new Promise(function () {
$.ajax({
url: "Validation/MyValidationMethod",
type: "POST",
data: {
value: value
},
//to keep reference
context: this
}).done(function (data) {
}, function () {});
$.ajax({
url: "Validation/MyValidationMethod",
type: "POST",
data: {
value: value
},
//to keep reference
context: this
}).done(function (data) {
//support the response to be a boolean
if (data === true)
return d.resolveWith(field, [{ field: field }]);
if (data === false)
data = { error: true };
data.field = field;
if (data.error) {
//define here the error message that you want to use
data.message = I.t("errors.invalidValue");
d.rejectWith(field, [data]);
} else {
d.resolveWith(field, [data]);
}
}).fail(function () {
//SERVER SIDE ERROR DURING VALIDATION: display an error message to let the user know that the validation failed because of a system error
//NB: the client side form could be right; but we cannot be sure of this, therefore we invalidate the field
d.reject({ error: true, message: I.t('errors.validationFailed') });
});
//return a promise object
return d.promise();
}
}
The custom validation rule can then be used inside validation schemas:
schema: {
property: {
validation: ["myAjaxRule"]
}
}