Answer the question
In order to leave comments, you need to log in
Data validation how to implement?
validate - data validation
Description
You need to implement the validate function to validate the data in the object.
The input is a set of data (for example, form data) and a set of rules for validation, described in a specific format.
It is necessary to understand whether the data complies with these rules and, if not, give out information - which data does not comply with which rules.
Input data:
data - an object, where keys are field names, and values are values of primitive types (not arrays/objects)
rules - an object with a set of rules, where keys are field names, and values are an object with validation rules. Rules written
Output data - object with fields:
result - boolean value, if there were no errors - true, there were - false
errors - if there were no errors - an empty array, if there were - an array of format objects with fields:
field - field name
value - field value
rule - name of the rule that the field did not match
Example:
var data = {
name: 'Alex',
age: 30,
profession:
};
var rules = {
name: { required: true, minLength: 1, maxLength: 3 },
age: { min: 18, max: 60 },
}
validate(data, rules); // { result: true, errors: [] }
data.age = 5;
validate(data, rules); // { result: false, errors: [{field: 'age', value: 30, error: 'max'}] }
Answer the question
In order to leave comments, you need to log in
Problems of this kind are standard and have been solved many times.
There are many libraries for data validation.
choose the right one and use it or write a wrapper
if your TK cannot be changed.
for example, one of the most popular libraries https://validatejs.org/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question