Monday 6 October 2014

x-mvc form validation

Standard
in new x-mvc i have added form validation it is so simple and usable

reference link : https://www.npmjs.org/package/x-mvc

How to use

Install from npm
npm install x-mvc
 
Instantiate a new form_validation object

req.library.load('form_validation');

/** construct a new form_validation object passing the data array to validate
  * date array should contain a set of objects formatted as following
  * {fieldName: value}
 */ 
var data = {
    name: 'foo bar',
    email: 'foo@bar.com'
}
var form_validation = new req.library.form_validation(data);
 
Add validation rules
/**
  * to add validation rules use addRule function
  * addRule accepts 3 arguments 
  * field Name as in data object
  * friendly Name for error messages
  * rules separated by |
  * rule is specified by a name and optionaly options
  * like for minLength you should also submit what is the minimum length 
  * using the brackets way [10]
 **/
form_validation.addRule('name', 'Name', 'required|minLength[10]');
 
Run validation rules
/**
  * run function go through all validation rules you specified for all fields
  * it accepts a callback function
  * where err is an array contains all error messages formatted like 
  * {fieldName: errorMessage }
  * or null if no errors have been found
  * and data is the data object 
 **/
form_validation.run(function(err, data){

});

Validation rule

required: validates that a value exists
minLength[l]: validates that a value length is at minimum equal to l
maxLength[l]: validates that a value length is at maximum equal to l
exactLength[l]: validates that a value length is exactly l
greaterThan[l]: validate that a value is greater than l
lessThan[l]: validates that a value is less than l
alpha: validates that a value contains only alphabet letters [A-Za-z]
alphaNumeric: validates that a value contains only alphabet letters or numbers [A-Za-z0-9]
alphaNumericDash: validates that a value contains only alphabet letters, numbers or dash [A-Za-z0-9-]
numeric: validates that a value is numeric [0-9]
integer: validates that a value is an integer
decimal: validates that a value is a decimal number
natural: validates that a value is a natural number >= 0
naturalNoZero: validates that a value is a natural number and greater than zero
email: validates that a value looks like an email
regex[s]: validates that a value matches the given regular expressions s
matches[f]: validates that a value matches a value of another field f
sanitize: sanitize a value against any possible xss attacks

 Example:

//add product
module.exports.add_product=function(req,res){
            data={title:"Add Product",sess:req.session,valid:''};
            res.render('add_product',data);
    };
//save product
module.exports.save_product=function(req,res){
    req.library.load('form_validation');
    var input = JSON.parse(JSON.stringify(req.body));
    var form_validation = new req.library.form_validation(input);
    form_validation.addRule('product_name', 'Product Name', 'required');
    form_validation.addRule('price', 'Price', 'required|numeric');
    form_validation.addRule('product_description', 'Product Description', 'required');
    form_validation.run(function(err, input){
        if(!err){
                var dt_join=Math.round(+new Date()/1000);
                var xip=require('x-image-processing');
                var product_image=req.files.product_pic;
                xip.upload(product_image,'./public/images/product/',dt_join);
                xip.resize('./public/images/product/thumb/',100,100);
                xip.crop('./public/images/product/crop/',100,100,20,20);
                var data = {
                    product_name    : input.product_name,
                    price : input.price,
                    product_description   : input.product_description,
                    product_slug: req.utility.slug(input.product_name),
                    customer_id: req.session.id,
                    post_date: dt_join,
                    status: 1
                    };
                req.models.product.create(data, function(err, rows) {
                    if(err){
                        console.log(err);
                    }
                    else{
                        data={
                            product_id:rows.id,
                            image_name: xip.getName(),
                            is_default: 1
                        }
                        req.models.product_image.create(data,function(err,rows){
                            if(err){
                                console.log(err);
                            }
                        req.session.msg="Add Successfully !";
                        req.session.css_class="green-msg";
                        res.redirect('my-product');
                        });
                    }
                });
            }
        else{
            console.log(err);
            data={title:"Add Product",sess:req.session,valid:err,input:input};
            res.render('add_product',data);
        }
    });
};