This is an empty project to start with noframework
git clone https://github.com/oussamahamdaoui/start-noframework.git
npm i
npm run watch
npm run build
ForgJs is a javascript lightweight object validator.
Home Page: https://oussamahamdaoui.github.io/forgjs-examples/
License: MIT License
This seems similar to http://objectmodel.js.org/.
Can you highlight some of the differences / reasons to use this library over ObjectModel?
Thanks!
Example:
const event = new Validator({
employeeId: new Rule({ type: 'string' }),
duration: new Rule({ type: 'int' })
})
event.test({
employeeId: '123',
duration: 10,
shouldNotBeHere: true
})
// returns false, this is OK
events.getErrors({
employeeId: '123',
duration: 10,
shouldNotBeHere: true
})
// returns [], this is not OK I think, should return at least [undefined] or even better: ['Unknown property found: "shouldNotBeThere"']
Hi! I have the following example:
// value is one of "", "ABCD1234"
const discountCode = new Rule({
type: 'string',
match: /^[A-Z0-9]$/,
optional: true,
minLength: 8,
maxLength: 8
}).test(value)
Setting the optional
property does not work here right now, because it requires the value to be either undefined or something that matches the Rule. I was curious if there is a possibility to state somewhere that ""
should be also acceptable? I could do either value = "" || ...
or
Rule({
type: 'string',
match: /^$|^[A-Z0-9]{8}$/
})
, just curious if there is a cleaner way?
This might be a stupid question, but how can I add a boolean rule in a validator?
in other words, if I have an object {a:1, b:true} I can test for a to be an integer, but how do I test for b to be a boolean?
Example
const validator = new Validator({
users: new Rule({
type: "array",
of: new Rule({type: "int", oneOf: [2, 3, 4, 5]}, "User ID does not exist")
}, "Users' ID not provided"),
});
validator.getErrors([2,4,7,10]) // returns Users' ID not provided
Validator.getErrors() methods returns a function definition for me and not a string.
Hi, I saw a reddit post asking for improvement suggestions in this repo. Here goes:
Puzzle Driven Development
and 0pdd for task management.If it sounds interesting and want more details, feel free to ask, I'll be glad to help.
Have fun!
Error handeling -> Error handling
Left TO DO for next relese -> Left TO DO for next release
Hey, I did a quick scan for the repo and I like what I see, I have written a Form library and I was seeking for some package like this one to fill out the validation part (didn't find something that I like so I write some light validation class inside my library). so I thinking about using this library,
some feature that I think will be great is to set the error message as a function for example:
const createMinIntRule = (num) => {
return new Rule(
{ type: 'integer', min: num },
(key, value) => `${key} must be greater then ${num}, ${value} is not enough`
)
}
and then you can create more reusability in your rules, let me know what do you think about it, I will love to make a pull request with implementation,
of course there that the option of a string as an error message will be still working.
const { Validator, Rule } = require('@cesium133/forgjs');
// test: use type at the start -- this will works
let validator = new Validator({
name: new Rule({ type: 'string', optional: false, notEmpty: true, minLength: 1 }),
description: new Rule({ type: 'string', optional: true }),
done: new Rule({ type: 'boolean', optional: true })
});
validator.test({ description: 'Just with description.' }); // return false
// test: use type at the end -- this will throw an Error
validator = new Validator({
name: new Rule({ optional: false, notEmpty: true, minLength: 1, type: 'string' }),
description: new Rule({ type: 'string', optional: true }),
done: new Rule({ type: 'boolean', optional: true })
});
validator.test({ description: 'Just with description.' }); // this throw an Error
Hey there. Loved the repo! I had a question though. How do you support nested Objects. Just for an example, if we have a object like
{ name: { first_name: 'John', last_name: 'Doe' }, address: { city: 'Mumbai', country: 'India' } }
How do we go about validating this?
Validating an undefined property will cause an error, e.g.:
const { Validator, Rule } = require('@cesium133/forgjs');
let validator = new Validator({
name: new Rule({ type: 'string', optional: false, notEmpty: true, minLength: 1 }),
});
// this will works
validator.test({ name: 'ok' }); // return true
// this will throw an exception
validator.test({ name: null }); // this throw an Error
(I'm using @cesium133/forgjs version "1.1.9)
Hello
there are a few mistakes in the example on README, I found the following - please see below the corrected code.
Corrected code:
const { Validator, Rule } = require('@cesium133/forgjs');
const emailRule = new Rule({
type: 'email',
user: user => user === 'dedede',
domain: domain => ['outlook', 'gmail', 'yahoo'].indexOf(domain) !== -1,
}, null);
const passwordRule = new Rule({
type: 'password',
minLength: 8,
uppercase: 1,
numbers: 1,
matchesOneOf: ['@', '_', '-', '.', '!'],
}, null);
const vComplexe = new Validator({
age: new Rule({ type: 'int', min: 18, max: 99 }),
dateOfBirth: new Rule({ type: 'date' }),
array: new Rule({ type: 'array', of: new Rule({ type: 'string' }) }),
email: emailRule,
password: passwordRule
});
vComplexe.test({
age: 26,
dateOfBirth: new Date(1995, 10, 3),
array: ['1'],
email: '[email protected];',
password: 'ad1_A@@Axs',
}); /// returns true
imagine
I want to validate any data, and show any message to user on error
so I must to do somethink like:
const result = prettyValidator.test(data);
if (!result) {
const errors = prettyValidator.getErrors(data);
procassErrors(errors); // in my case -> res.status(422).send(errors);
return;
}
go on...
so I must to go through this cycle twice on error. and my data can contains lot of fields.
well, i can do this:
const errors= prettyValidator.getErrors(data);
if (errors.length > 0) {
res.status(422).send(errors);
return;
}
go on...
these performance is better, but the syntax is not semantic - looks like I expect an error.
and the result is not semantic - I expect an empty array on success
I recommend you to generate the errorArray in the test method too, but return true on success and throw errorArray on error.
this will allow to use try/catch and write more clean code
Take this example:
new Rule({
type: "string",
notEmpty: false
})
.test("") // should return true
Example:
const validator = new Validator({
str: new Rule(
{ type: 'string' },
'Error message'
)
});
validator.getErrors({
str: undefined,
}); // Error thrown: Cannot read property 'constructor' of undefined
Expected behavior: [ 'Error message' ]
P.S. null and undefined have no constructor in JS
this package is awesome. thnk you!
suggestion for the functionality extands.
it will be very usefull to check required and allowed keys in anobject
Validating a null property will cause an error, e.g.:
const { Validator, Rule } = require('@cesium133/forgjs');
let validator = new Validator({
name: new Rule({ type: 'string', optional: false, notEmpty: true, minLength: 1 }),
});
// this will works
validator.test({ name: 'ok' }); // return true
// this will throw an exception
validator.test({ name: null }); // this throw an Error
Example:
const { Validator, Rule } = require('@cesium133/forgjs');
const validator = new Validator({
value: new Rule(
{
type: 'int|float',
min: 1
},
'Error message'
),
});
validator.getErrors({
value: 0,
}); // [ 'Error message', 'Error message' ]
One rule, one custom error message, but multiple errors in array.
I was trying to fix it and send a PR, but it seems like you have unfinished or undocumented work there.
Add more doc in the code urgent the Validator class
Hi there,
I'm trying to use forgJS with create-react-app but unfortunately it raise the error:
1!] Error: 'Rule' is not exported by node_modules/@cesium133/forgjs/index.js
this is how I used:
import * as React from 'react';
import { Rule } from '@cesium133/forgjs';
import styles from './styles.css';
const ExampleComponent = ({ text }: any) => {
const floatRule = new Rule(
{
type: 'float',
min: 100,
},
null
);
const result = floatRule.test(200.3);
console.log(result);
return <div className={styles.test}>Example Component: {text}</div>;
};
export default ExampleComponent;
To have a working example is enough to do:
npx create-react-library
and then install the package forgJs.
Can someone help me on that please?
Hey every one, If you have suggestions or ideas to improuve the code please feel free to let a comment here.
Rulles:
const someRule= new Rule({
type: 'yourType',
prop1: val1,
prop2: val2, ...
}, null);
someRule.test(validValue) // returns true
someRule.test(invalidValue) // returns false
[ci skip]
to your commit messagecode with love ❤️
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.