Giter VIP home page Giter VIP logo

js-validator-livr's People

Contributors

danielhreben avatar dependabot[bot] avatar koorchik avatar pterolex avatar reiz avatar spaintrain avatar striped-s0cks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

js-validator-livr's Issues

Validate Rule Format

Hello there,

is there any way to validate a rule? I mean, if I create a rule that is not valid, only fails while validating, but not in the constructor. For instance,

const livr = require('livr');

const validator = new livr.Validator("I'm not a rule");
validator.validate({ prop: 'whatever' });

Returns the following error Rule [I] not registered in the validate method

Proposed Solution

Throw an error in the Validator constructor. Invoking a validateRule method before creating the Validator object.
Another possible solution could be adding a public method for validating the rule. In this way, we have a way to validate the rule before creating the Validator.

Пример вывода осмысленного сообщения вместо кода ошибки

Было бы здорово добавить простейший пример для не очень понимающих :)
Для меня логично сделать массив для всех кодов, на требуемом языке:

var messages ={
   'required': 'Требуемое поле',
   'not_empty': 'Не может быть пустым',
   'max_length': 'Не больше %s символов'
}

Дальше неясно, как с минимальным оверхедом вместо ошибки подставить развёрнутый текст:

var validator = new LIVR.Validator({}),
      validData = validator.validate(formSerializedData);

if (validData) {
	// отправляем
} else {
	if (validator.errors) {
		$.each(validator.errors, function(field, error) {
			showMessage(field, error); // ссылка на поле, код ошибки
		});
	}
}

Утилиты для написания собственных правил

Почти во всех правилах нужно следующее:

if (value === undefined || value === null || value === '' ) return;
if (!util.isNumberOrString(value)) return 'FORMAT_ERROR';
value += '';

Может, добавить методы utils.isNotEmpty и utils.numToString, а ссылку на utils сделать доступной снаружи?

String fields in nested object are trimmed by default

Rule:
{ testObj: ['required', {nested_object: { testField: 'string' }}] }

Data:
{ testObj: { testField: " qwertyuio " } }

Actual Output:
{ "testObj": { "testField": "qwertyuio" } }

Expected Output:
{ "testObj": { "testField": " qwertyuio " } }

http://livr-multi-playground.webbylab.com/#%7B%22rules%22%3A%22%7B%5Cn%20%20%20%20testObj%3A%20%5B'required'%2C%20%7Bnested_object%3A%20%7B%5Cn%20%20%20%20%20%20%20%20testField%3A%20'string'%5Cn%20%20%20%20%7D%7D%5D%5Cn%7D%22%2C%22input%22%3A%22%7B%5Cn%20%20%20%20testObj%3A%20%7B%5Cn%20%20%20%20%20%20%20%20testField%3A%20%5C%22%20%20qwertyuio%20%20%5C%22%5Cn%20%20%20%20%7D%5Cn%7D%22%7D

Trimming by default is not expected behavior. trim rule should do it

Правило optional

Можно добавить правило-пустышку optional, чтобы указывать в схеме необязательные поля, не требующие валидации.

{
  "name": "optional", 
}

Сейчас приходится делать так:

{
  "name": [], 
}

list_of_objects and list_of_different_objects have different behaviour on error

list_of_different_objects also returns "FORMAT_ERROR" in results array. This can lead to showing error messages on wrong objects in real apps.

{
    "products": [
        "FORMAT_ERROR",
        {
            "quantity": "TOO_LOW"
        },
        null,
        null,
        null
    ]
}

With typical error-handling code this will show "quantity": "TOO_LOW" error on the products[1], while the error is in products[0]

Examples in playground:
http://webbylab.github.io/livr-playground/#{%22rules%22%3A%22{\n%20%20%20%20order_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20products%3A%20[%20%27not_empty_list%27%2C%20{%20%27list_of_objects%27%3A%20{\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20product_type%3A%20%27required%27%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20material_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20quantity%3A%20[%27required%27%2C%20{%27min_number%27%3A%201}%20]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20warehouse_id%3A%20%27positive_integer%27\n%20%20%20%20%20%20%20%20%20%20%20%20}}]\n}%22%2C%22data%22%3A%22{\n%20%20%20%20order_id%3A%2010455%2C\n%20%20%20%20products%3A%20[{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%200%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%205%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%205%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}]\n}%22}

http://webbylab.github.io/livr-playground/#{%22rules%22%3A%22{\n%20%20%20%20order_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20products%3A%20[%27required%27%2C%20{%20%27list_of_different_objects%27%3A%20[\n%20%20%20%20%20%20%20%20product_type%2C%20{\n%20%20%20%20%20%20%20%20%20%20%20%20material%3A%20{\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20product_type%3A%20%27required%27%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20material_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20quantity%3A%20[%27required%27%2C%20{%27min_number%27%3A%201}%20]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20warehouse_id%3A%20%27positive_integer%27\n%20%20%20%20%20%20%20%20%20%20%20%20}%2C\n%20%20%20%20%20%20%20%20%20%20%20%20service%3A%20{\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20product_type%3A%20%27required%27%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20name%3A%20[%27required%27%2C%20{%27max_length%27%3A%2020}%20]\n%20%20%20%20%20%20%20%20%20%20%20%20}\n%20%20%20%20%20%20%20%20}\n%20%20%20%20]}]\n}%22%2C%22data%22%3A%22{\n%20%20%20%20order_id%3A%2010455%2C\n%20%20%20%20products%3A%20[123%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%200%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%205%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%205%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{\n%20%20%20%20%20%20%20%20product_type%3A%20%27service%27%2C\n%20%20%20%20%20%20%20%20name%3A%20%27Clean%20filter%27\n%20%20%20%20}]\n}%22}

IE11 support

Поддерживает ли JS реализация IE11?
image

How to describe a rule for a list of different objects?

I am trying to describe an object of this kind:

{
    operations: [
        {
            properties:{
            	type:"1",
              	group: "11",
              	data:{data1:{},
                      data2:{}
                     }
            }
        },
        {
            properties:{
            	type:"2",
              	group: "12",
              	tools:["tools1","tools2"]
            }
        },
        {
            properties:{
            	type:"3",
              	group: "13",
              	objList:[{},{}]
            }
        },
        {
            properties:{
            	type:"4",
              	group: "14"
            }
        }
    ]
}

How can i use "variable_object" for such an object?

rule with multiple arguments

Подскажите, допустим есть js-объект типа {email: '[email protected], useEmail: false}. Есть ли возможность написать правило, в которое на вход попадает два поля: email и useEmail? Т.е. мне нужно валидировать емеил только, если он используется.
И спасибо за валидатор! Он развязал руки и упростил разработку ))

Async interface for validation rules

Не увидел в документации ничего про асинхронные правила. Без этого может быть тяжко на клиенте: например, валидация города / улицы, надо скачивать список с сервака, а интерфейс валидатора синхронный.

Дефолтное значение

Привет :)
Можно добавить поддержку правил следующего вида:

  default_value: function (defaultValue) {
    return function (value, params, outputArr) {
      if (isNoValue(value)) outputArr.push(defaultValue);
    };
  }

то есть, если нет значения подставляем дефолтное...

iso_date rule

После строки

d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);

изменяется число на предыдущее. После чего проверка

d.getDate() == +matched[3]

не выполняется.

Cannot add 2 list_of_different_objects rules for the same field

I have the following json:

{
  "id": 123,
  "pricingInfos": [
    {
      "period": "MONTHLY",
      "price": "20000",
      "businessType": "RENTAL",
    },
    {
      "price": "100000",
      "businessType": "SALE",
    }
  ]
}

I have this rule that adds 2 list_of_different_objects to the same pricingInfos field:

{
  "id": ["required", "positive_integer"],
  "pricingInfos": ["required",
    {
      "list_of_different_objects": ["period", {
          "DAILY": {"price": ["required", {"number_between": [3, 30000]}]},
          "WEEKLY": {"price": ["required", {"number_between": [25, 255000]}]},
          "MONTHLY": {"price": ["required", {"number_between": [100, 900000]}]},
          "YEARLY": {"price": ["required", {"number_between": [1200, 10800000]}]}
        }]
    },
    {
      "list_of_different_objects": ["businessType", {
          "SALE": {"price": ["required", {"number_between": [10000, 1000000000]}]},
          "RENTAL": {"period": "required"}
        }]
    }
  ]
}

Looks like it completely ignores both list_of_different_objects since the rules are not used (I can insert invalid values and no errors are detected).

Here is the playbook with that simulates the bug:

http://webbylab.github.io/livr-playground/#%7B%22rules%22%3A%22%7B%5Cn%20%20%5C%22id%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%5C%22positive_integer%5C%22%5D%2C%5Cn%20%20%5C%22pricingInfos%5C%22%3A%20%5B%5C%22required%5C%22%2C%5Cn%20%20%20%20%7B%5Cn%20%20%20%20%20%20%5C%22list_of_different_objects%5C%22%3A%20%5B%5C%22period%5C%22%2C%20%7B%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22DAILY%5C%22%3A%20%7B%5C%22price%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%7B%5C%22number_between%5C%22%3A%20%5B3%2C%2030000%5D%7D%5D%7D%2C%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22WEEKLY%5C%22%3A%20%7B%5C%22price%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%7B%5C%22number_between%5C%22%3A%20%5B25%2C%20255000%5D%7D%5D%7D%2C%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22MONTHLY%5C%22%3A%20%7B%5C%22price%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%7B%5C%22number_between%5C%22%3A%20%5B100%2C%20900000%5D%7D%5D%7D%2C%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22YEARLY%5C%22%3A%20%7B%5C%22price%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%7B%5C%22number_between%5C%22%3A%20%5B1200%2C%2010800000%5D%7D%5D%7D%5Cn%20%20%20%20%20%20%20%20%7D%5D%5Cn%20%20%20%20%7D%2C%5Cn%20%20%20%20%7B%5Cn%20%20%20%20%20%20%5C%22list_of_different_objects%5C%22%3A%20%5B%5C%22businessType%5C%22%2C%20%7B%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22SALE%5C%22%3A%20%7B%5C%22price%5C%22%3A%20%5B%5C%22required%5C%22%2C%20%7B%5C%22number_between%5C%22%3A%20%5B10000%2C%201000000000%5D%7D%5D%7D%2C%5Cn%20%20%20%20%20%20%20%20%20%20%5C%22RENTAL%5C%22%3A%20%7B%5C%22period%5C%22%3A%20%5C%22required%5C%22%7D%5Cn%20%20%20%20%20%20%20%20%7D%5D%5Cn%20%20%20%20%7D%5Cn%20%20%5D%5Cn%7D%22%2C%22data%22%3A%22%7B%5Cn%20%20%5C%22id%5C%22%3A%20123%2C%5Cn%20%20%5C%22pricingInfos%5C%22%3A%20%5B%5Cn%20%20%20%20%7B%5Cn%20%20%20%20%20%20%5C%22period%5C%22%3A%20%5C%22MONTHLY%5C%22%2C%5Cn%20%20%20%20%20%20%5C%22price%5C%22%3A%20%5C%2220000%5C%22%2C%5Cn%20%20%20%20%20%20%5C%22businessType%5C%22%3A%20%5C%22RENTAL%5C%22%2C%5Cn%20%20%20%20%7D%2C%5Cn%20%20%20%20%7B%5Cn%20%20%20%20%20%20%5C%22price%5C%22%3A%20%5C%221%5C%22%2C%5Cn%20%20%20%20%20%20%5C%22businessType%5C%22%3A%20%5C%22SALE%5C%22%2C%5Cn%20%20%20%20%7D%5Cn%20%20%5D%5Cn%7D%22%7D

Describe a rule for an array

What would be the rule to describe an array? In all examples that I've found arrays exists only as a property in some object. How can we describe an array not inside some object ?
like:
const input = [{a: 1, b: 2}, {a: 3, b: 4}];

list_of_different_objects ignores unknown objects

http://webbylab.github.io/livr-playground/#{%22rules%22%3A%22{\n%20%20%20%20order_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20products%3A%20[%27required%27%2C%20{%20%27list_of_different_objects%27%3A%20[\n%20%20%20%20%20%20%20%20product_type%2C%20{\n%20%20%20%20%20%20%20%20%20%20%20%20material%3A%20{\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20product_type%3A%20%27required%27%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20material_id%3A%20[%27required%27%2C%20%27positive_integer%27]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20quantity%3A%20[%27required%27%2C%20{%27min_number%27%3A%201}%20]%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20warehouse_id%3A%20%27positive_integer%27\n%20%20%20%20%20%20%20%20%20%20%20%20}%2C\n%20%20%20%20%20%20%20%20%20%20%20%20service%3A%20{\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20product_type%3A%20%27required%27%2C\n%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20name%3A%20[%27required%27%2C%20{%27max_length%27%3A%2020}%20]\n%20%20%20%20%20%20%20%20%20%20%20%20}\n%20%20%20%20%20%20%20%20}\n%20%20%20%20]}]\n}%22%2C%22data%22%3A%22{\n%20%20%20%20order_id%3A%2010455%2C\n%20%20%20%20products%3A%20[{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%201%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27ostrich%27%2C\n%20%20%20%20%20%20%20%20legs_count%3A2\n%20%20%20%20}%2C{%20\n%20%20%20%20%20%20%20%20product_type%3A%20%27material%27%2C\n%20%20%20%20%20%20%20%20material_id%3A%20345%2C\n%20%20%20%20%20%20%20%20quantity%3A%20%205%2C\n%20%20%20%20%20%20%20%20warehouse_id%3A%2024\n%20%20%20%20}%2C{\n%20%20%20%20%20%20%20%20product_type%3A%20%27service%27%2C\n%20%20%20%20%20%20%20%20name%3A%20%27Clean%20filter%27\n%20%20%20%20}]\n}%22}

Used example from readme. Invalid object types just get ignored. May be there's a way to limit this objects by adding something to the rules? Then this is not an issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.