B
B
badman42352020-03-08 09:43:17
JavaScript
badman4235, 2020-03-08 09:43:17

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'}] }


A set of possible rules (parameter in brackets):

required (bool) - the field is contained in the object and is not equal to null. If required is not in the rules, the field is considered optional.
isString (bool) - field is a string
isNumber (bool) - field is a valid number
isBoolean (bool) - field is a boolean value
minLength (number) - field is a string with a length greater than or equal to
maxLength (number) - field - is a string with a length less than or equal to the
min (number) parameter - field is a number greater than or equal to the
max (number) parameter - field is a number less than or equal to the
isEmail (bool) parameter - field is a valid email (basic validation, without complex cases)

Link to the taskhttps://repl.it/@maxJnyk/validate-3 (some of my code is already written there, but not everything is validated)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-08
@Che603000

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 question

Ask a Question

731 491 924 answers to any question