2.0.0 • Published 6 years ago
form-validation-thieny v2.0.0
Introduction
This lib use for validate javascript form data object send to API before we using this data. Reuse any type of data we defined.
Example
var thieny = require('form-validation-thieny');
let data = {
email: 'testing@testing.local',
new_email: 'new_email@testing.local'
};
let result = thieny.required('email') // could be array ['email']
.optional('new_email', 'old_email') // could be array ['new_email', 'old_email']
.validate(data);
console.log(result);
// success
// {
// error: null,
// value: {
// email: 'testing@testing.local',
// new_email: 'new_email@testing.local'
// }
// }
// any error
// {
// error: {
// code: 1,
// msg: 'Invalid email'
// },
// value: {}
// }Try Online Demo
Before do validate, just defined object type and put them when your app start (run first)
// add new type defined email type and error that you want to response
thieny.add_type({
type_name: 'email',
error_data: {
code: 1,
msg: 'Invalid email'
},
validate: str => {
if (str) {
return {
value: str
};
} else {
return {
error: true
}
}
},
field_names: [{
name: 'new_email'
}, {
name: 'old_email',
error_data: {
code: 4,
msg: 'Invalid old email'
}
}]
});Usage
add_type
Add new type
type_nameString name of typeerror_dataAny error object return when invalid data.validateFunction function validate data: Can be yourself function or using @hapi/joi module
Your function
validate: str => {
// your validate function here
if (str) {
return {
value: str
};
} else {
return {
error: true
}
}
}Using @hapi/joi Reference API Reference.
validate: str => {
// using @hapi/joi
return thieny.joi.string().trim().replace(/[^0-9]/g, '').length(10).validate(str);
}Return an object
errorBoolean optional true/falsevalueAny value of input after validatefield_namesArray optional list of fields had the same typenameerror_dataoptional error object return when invalid data
required
List of field (arg or array) are required in input data
optional
List of field (arg or array) are optional in input data
validate
Validate an object data Return an object
errorAny error_data which you defined before in add_typevalueObject An object was return if no error after validate.