koorchik / js-validator-livr Goto Github PK
View Code? Open in Web Editor NEWLightweight javascript validator supporting Language Independent Validation Rules Specification (LIVR)
License: MIT License
Lightweight javascript validator supporting Language Independent Validation Rules Specification (LIVR)
License: MIT License
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
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); // ссылка на поле, код ошибки
});
}
}
According to this proposal the question arises: should the rules for arrays be added?
Got an error while validate 1e-7
, typeof is "number".
Почти во всех правилах нужно следующее:
if (value === undefined || value === null || value === '' ) return;
if (!util.isNumberOrString(value)) return 'FORMAT_ERROR';
value += '';
Может, добавить методы utils.isNotEmpty
и utils.numToString
, а ссылку на utils
сделать доступной снаружи?
Hi,
Is it okay that https://www.google.
is valid?
would be great if someone could fix that
Rule:
{ testObj: ['required', {nested_object: { testField: 'string' }}] }
Data:
{ testObj: { testField: " qwertyuio " } }
Actual Output:
{ "testObj": { "testField": "qwertyuio" } }
Expected Output:
{ "testObj": { "testField": " qwertyuio " } }
Trimming by default is not expected behavior. trim
rule should do it
Можно добавить правило-пустышку optional
, чтобы указывать в схеме необязательные поля, не требующие валидации.
{
"name": "optional",
}
Сейчас приходится делать так:
{
"name": [],
}
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]
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?
Подскажите, допустим есть js-объект типа {email: '[email protected], useEmail: false}. Есть ли возможность написать правило, в которое на вход попадает два поля: email и useEmail? Т.е. мне нужно валидировать емеил только, если он используется.
И спасибо за валидатор! Он развязал руки и упростил разработку ))
Не увидел в документации ничего про асинхронные правила. Без этого может быть тяжко на клиенте: например, валидация города / улицы, надо скачивать список с сервака, а интерфейс валидатора синхронный.
Привет :)
Можно добавить поддержку правил следующего вида:
default_value: function (defaultValue) {
return function (value, params, outputArr) {
if (isNoValue(value)) outputArr.push(defaultValue);
};
}
то есть, если нет значения подставляем дефолтное...
JS livr version is affected along with Java, Perl and Ruby
https://livr-playground.herokuapp.com/#%7B%22rules%22%3A%22%7B%5Cn%20%20%5C%22email%5C%22%3A%20%5B%5C%22email%5C%22%5D%5Cn%7D%22%2C%22input%22%3A%22%7B%5Cn%20%20%5C%22email%5C%22%3A%5C%22qwe%2Bcaf_%3D4evnlldiziyrfbozh7wgx5k3x%3Dololo.domain.com%40test.com%5C%22%2C%5Cn%7D%22%7D
После строки
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
изменяется число на предыдущее. После чего проверка
d.getDate() == +matched[3]
не выполняется.
https://github.com/koorchik/js-validator-livr/blob/master/lib/LIVR/Rules/Filters.js#L7
Насколько я понял, вторым аргументом передаётся объект с данными. А значит, выражение value === undefined
всегда будет ложным.
Реализация считает что true != true
Пример:
http://webbylab.github.io/livr-playground/#%7B%22rules%22%3A%22%7Btest%3A%20%7Bone_of%3A%5Btrue%2C%20false%5D%7D%7D%22%2C%22data%22%3A%22%7Btest%3A%20true%7D%22%7D
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:
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}];
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.