Exercise tracker needs validation

I’ve gotten the 4th test to pass, but not with validation. I have been researching different ways to validate, and have tried express-validation and mongoose-validation, but it seems like validation is already set up by fcc because I get a default Validation failed Response when I submit the form with a blank name, and the app crashes. I need a good tutorial on how to validate form input using whatever fcc is using. I don’t want to go further without being able to understand what has to happen with validation.

**Your code so far**
const express = require('express')
//const {body, validationResult} = require('express-validator')
//already using mongoose validator
const mongoose = require('mongoose')
//const validate = require('mongoose-validator')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors')
const db = process.env.DB_URI;
const usernameValidator = [
    validator: 'isLength',
    arguments: [1],
    message: 'Username should be at least {ARGS[0]} characters long.'
app.use(cors(), function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");

mongoose.connect(db, {useNewUrlParser:true, useUnifiedTopology:true, useFindAndModify: false});

const exerciseSchema = new mongoose.Schema({
  description: {type: String, required: true},
  duration: {type: Number, required: true},
  date: {type: String, required: true}
const userSchema = new mongoose.Schema({
  username: {type:String, required: [true, 'username required']},
  log: [exerciseSchema]

const Exercise = mongoose.model('Exercise', exerciseSchema);
const User = mongoose.model('User', userSchema);
//create a schema and model for users, then add
//to db and make sure 
//response includes _id
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
You can POST to /api/users with form data username to create a new user. The returned response will be an object with username and _id properties.

app.post('/api/users', bodyParser.urlencoded({extended:false}), (req, res) => {
  console.log("got this far")
  if(Error) {
    //res.send('Username is required. Please reload form and try again.'); crashes
    return console.error(Error);//would lke to reload form page here
  let newUser = new User({
  //saves the User to the db and returns the username id properties as json with the response
  newUser.save((err, savedUser) => {    
    if (err) {
      return console.error(err);
      username: savedUser.username,
      _id: savedUser._id

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Exercise Tracker

Link to the challenge:


Can you setup a project in repl.it so we can see what you have done? Because if that’s all the code you’re using, it would never work.

Now, assuming that’s not your entire code and just the routes, the test doesn’t care which validator (you can solve it without using one), it cares about the responses you return.

The tests are shown on the project’s page, but if that doesn’t help:

  • Check the developer console on your browser to see what is returned from your project and compare it to what the tests expect. To do this, before you submit the project (on the project page), press the keys Control + Shift + i, F12 or right click on any element of the page and then Inspect Element. After that, check the tabs Console and Network (this tab will all the requests your browser does to the server).
  • Check your project’s console. If you’re using repl.it, the console will show you the errors so you can debug it:

With those tools you should be able to debug it :slight_smile:.

Hi! Thanks for the response. I haven’t had a chance to work through your suggestions yet, but I think I didn’t explain my issue very well.
I want to handle the situation where a user submits an empty form without crashing the app using validation and I’ve tried several ways to do it but the app crashes anyway, so I am missing something, probably quite obvious, having to do with the implementation of validation. Like maybe I’m putting the code in the wrong place, or the code isn’t validating whether the input is an empty string, or something. Been staring at it until it has stopped making sense…

1 Like

I see!

The express-validator is meant to be used as a middleware for your routes, to validate user input directly, whereas mongoose-validator is meant to be used to validate your model data before it gets saved.

This may seem to be the same, but depending on the context it may be different. In this context, however, it’s pretty much the same.

Using express-validator though, you should create a validator for the route like this:

const { validate, ValidationError, Joi } = require('express-validation');
const exerciseObj = Joi.object({
  // Here you add the rules for the exercise object
const userObj = Joi.object({
    username: Joi.string()
    log: [exerciseObj],

app.post('/api/users', [
  validate({body: userObj}),
  (req, res) => {
    // Here you add the code to create the user and save it to mongo

// A global error handler
// This is not strictly necessary, but it helps you debug
// and gives you a better description of what happened
app.use((err, req, res, next) => {
  if (!err) {
    return next();
  if (err instanceof ValidationError) {
    return res.status(err.statusCode).json(err)

  console.error('The request failed:', err);
    error: 'We could not process your request',
    status: 'error'

Check this repl.it:

When I send a valid username:

If a send nothing:

And so on. I used the extension RESTer for Firefox to test it, in case you want to try.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.