Search code examples
javascriptvalidationfeathersjs

How can I validate Date format in FeatherJS


I am trying to validate user input send a notification when the user types wrong input. This is what I have so far.

const { BadRequest } = require('@feathersjs/errors');

module.exports = function () {
  return async  context=> {
    const { data } = context;
    if(typeof data.taskid !== 'string' || data.taskid.trim() === '') {
      throw new BadRequest('TaskId is invalid.');
    }
    if(typeof data.testresource !== 'string' || data.testresource.trim() === '') {
      throw new BadRequest('Test resource is invalid.');
    }
    //need check again
    if((new Date(data.startdate)).getTime() < 0) {
      throw new BadRequest('Start date must be a date');
    return context;
  };
};

The problem is validating date doesn't right when I test. Thank for your time.


Solution

  • Try to use Moment JS to validate the Date you can also use this to format dates , Set Timezone etc.

    https://momentjs.com/

    https://www.htmlgoodies.com/beyond/javascript/date-validation-using-moment.js.html

    if(moment(data.startdate,["MM-DD-YYYY", "YYYY-MM-DD"],true).isValid()==false) {
       throw new BadRequest('Start date must be a date');
    }