Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add custom methods in checkit module?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 509
    Comment on it

    Sometimes, you may have a long conditions to check for validity. In general, you may need to check certain thing that doesn't exists in checkit module, In that case you extends checkit module and add custom methods into it.

     

    For ex.- To write a custom method for checking date:

    To inherit a class you use:

    Classname.protype.new_method = function(value) {
    
    //The definition goes here
    
    }

     

    Calling the newly created method, the rule is as follows:-

    const rules = {
     dob: ['required', { rule: 'date:value', message: 'dob must be a valid date.' }],
    }

    date:value: Here, date is the name of custom method and value is the parameter that is in user data or payload.

     

    Code:

    const checkIt = require('checkit');
    Checkit.Validator.prototype.date = function date(value) {
     if (moment(value, 'MM/DD/YYYY', true).isValid() ||
      moment(value, 'MM-DD-YYYY', true).isValid()) {
      return true;
     }
     return false;
    };
    
    const payload = {name: "dinesh rawat", dob: "05/08/1988"};
    
    const rules = {
     dob: ['required', { rule: 'date:value', message: 'dob must be a valid date.' }],
    }
    
    const checkit = new Checkit(rules);
    
    return checkit.run(payload).then(validated => next()).then(Checkit.Error,
     err => responseObj.invalidPayload({ error: err }));

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: