node package manager


Express form new generation validator

Express Form New Generation


It need tests. I can't say that it's stable

I'm not dividing on filters and validators...for me it's called rules If rule modifies variable content it starts from to, remove, parse or something else as we say in everyday life If rules validating variable contents it starts from is At now this rules are available:

  call - { call: { func: function(field. fieldName, opts){} }}
  removeIfEmpty - Will remove [], {}, '', null, false, undefined ...
  match - { match: { regexp: /exp/, message: '' } }

It's simple. I guess example will say more than i can:

  var formng = require('formng')
    , body = {
        id: '15',
        foo: ' <script> alert(1); </script><h1>some &nbsp; HTML</h1>     ',
        bar: '  ',
        baz: 'abc'
  var form = formng({
    id: [ 'removeIfEmpty', parseInt ], // Here we call some rule and builtin js function `parseInt` 
    foo: [ 'trim', 'required', 'entityEncode' ],
    bar: [ 'trim', 'required' ], // Will call next(new Error()) because `bar` was trimmed and empty now 
    baz: [ function(field, fieldName, opts){
      return field + 'def';
    }, /^abcdef$/ ], // Here i have defined custom function, that concats `baz` value with 'def' string, after tests whether the `baz` matching /^abcdef$/ regexp  
    // Rules with options 
    faz: {
      match: { reqexp: /^a.+/, message: '%s not matching regexp' }
    // We can also validate nested json, but this technics not optimized yet...if you interested in that - look into the code or feel free to contact with me 
  app.get('/', function(req, res, next){
    // Here we will set `req.body` 
    req.body = body;
  }, form, function(req, res, next){
    res.send('Passed') // You will not see this without modifying `body` with it :) 

It can be any function that expects value as first arg and returns value Or function like this:

  function(fieldValue, fieldName, optsPassed) {
    return 'some string to set new value'
    return false // to throw an error 
    return null // to remove field from req.body 
    // or return nothing(undefined) to save the value 

It tryes to find .message attr in rule attributes(if presented, if not - default will be used)o If using custom validation function...we can just add message to opts object All errors passing to the next(new Error('message')) Formng will finish checking and redirect user to error route on first error found.

return false - validation error. return undefined - do not modify the field, that rule was validation rule< not filter return null - delete field from body

Everything excepts all above will modify field value If false|undefined|null value is needed this function will help you(just pass it as a rule):

    function(field, fieldName, opts){
        this.set(fieldName, null/* false or undefined */)
    } can manualy write rules. See node_modules/formng/rules