Express JS form validation using hapi/Joi fails to accurately validate the input data in forms

I am currently facing an issue with my form validation using the hapi/Joi package. The problem is that the schema keys are all taking the value of "undefined", which results in the first validation error being returned. How can I resolve this issue? Additionally, I would like to know if there is a way to display errors to the user without refreshing the page in Express. If so, please provide guidance on how to achieve this.

Here is my Express code:

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const Joi = require('@hapi/joi');
const uuidv4 = require('uuid/v4');

app.set('view engine','ejs');

const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname + '/public')));

app.get('/',(req,res)=>{
    res.render('main');
});

const schema = Joi.object().keys({
    name: Joi.string().min(3).required(),
    surname: Joi.string().min(5).required(),
    age: Joi.number().integer(),
    email: Joi.string().email({minDomainSegments: 2}).required(),
    password: Joi.string().min(3).required(),
    confirm: Joi.any().valid(Joi.ref('password'))
});

app.post('/register',(req,res)=>{
    req.body.id = uuidv4();
    console.log(req.body);
    const result = Joi.validate({

        name: req.body.name,
        surname: req.body.surname,
        age: req.body.age,
        email: req.body.email,
        password: req.body.password,
        confirm: req.body.confirm

    }, schema,(error,value)=>{
        if(error){

            printError(error);

        }
        else{
            console.log('success');
        }
    });

});

function printError(error){
    console.log(error);
}

app.listen(3000);

Below is my form:

<form action="/register" method="POST" enctype="multipart/form-data">

        <input type="text" name='name' class="form-control" value="">
        <input type="text" name='surname' class="form-control" value="">
        <input type="number" name='age' class="form-control" value="">
        <input type="email" name='email' class="form-control" value="">
        <input type="password" name='password' class="form-control">
        <input type="password" name='confirm' class="form-control">
        <input type="submit" class="btn btn-block btn-success" value="OKAY">

    </form>

The error message received:

{ ValidationError: child "name" fails because ["name" is required]
    at Object.exports.process (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\errors.js:202:19)
    at internals.Object._validateWithOptions (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\types\any\index.js:763:31)
    at module.exports.internals.Any.root.validate (C:\xampp\htdocs\express+mongo\node_modules\@hapi\joi\lib\index.js:145:23)
    at app.post (C:\xampp\htdocs\express+mongo\index.js:31:24)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
    at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:335:12)
  isJoi: true,
  name: 'ValidationError',
  details:
   [ { message: '"name" is required',
       path: [Array],
       type: 'any.required',
       context: [Object] } ],
  _object:
   { name: undefined,
     surname: undefined,
     age: undefined,
     email: undefined,
     password: undefined,
     confirm: undefined },
  annotate: [Function] }

Despite filling in the input fields in the form and submitting, the error "name is required" is displayed.

Answer №1

Update

const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

with

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Struggling to place buttons below each row in a Bootstrap DataTable, unfortunately, they are only appearing under a specific column rather than the entire row

I have developed a system for managing event expenses that includes an option for multiple installments of a single payment for each event. My goal is to display these installments when a user hovers over an event in the table, with each row representing a ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

The chef cookbook is unable to execute sqllocaldb using the execute resource

Struggling with this cookbook has been a challenge for some time. I've been attempting to set up various resources, including the Azure SDK, on a Windows Server 2012 R2 instance. Initially, I encountered the following error in the stack trace: Gene ...

Get started by setting up and utilizing react version 0.14.0 on your

I'm currently facing an issue in my project while using react-0.14.0. The error message I'm encountering is: Invariant Violation: ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copie ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

Strategies for handling user typos in a JavaScript prompt

Hi there! Just wanted to say that I'm new to this website, so please forgive any posting mistakes I might make. I'm currently taking a web technology class where we're learning JavaScript. In a previous lesson, we covered HTML5 and CSS. Our ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Tips for detecting when no checkboxes in a group are selected or when at least one checkbox is selected, and then applying a class to the corresponding div

<div class="accordion-group"> <div class="accordion-heading"> <a href="#collapse" data-parent="#accordionQuiz" data-toggle="collapse1.." class="accordion-toggle"> <strong>1...</strong> Question ...

How can I prevent my Vue.js application from losing focus when navigating to different components?

I am encountering an issue with my Vue.js app where the focus is lost when changing routes. Initially, when the site loads, the first element of the header component is correctly in focus as desired. However, when navigating to a different link on the site ...

Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs. Here is an exam ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

Guide on inputting information into a dual-column table where one column is linked to the other

After successfully inserting data with hardcoded values to verify the relation between the 2 columns, I am now wondering if there is a way to reference the value of id in reply_id. This is how I manually inserted data: const { data, error } = await su ...

I am looking to build an array that can store five numbers inputted by the user. Following that, I want to utilize a for loop to display the contents of the array. How can I accomplish this task?

Looking for help to store 5 unknown numbers in an array and then display them after the user has entered all 5 numbers. Can anyone assist me in creating an array of size 5 and using a for loop to show the numbers? Here is the code I currently have: ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

Instructions for activating and deactivating a numerical input field with a checkbox

Is there a way to create a pair of a checkbox and number field that are linked together? When the checkbox is clicked, it should disable the associated number field. Javascript File: $(document).ready(function(){ $("input[name=check]").click(function(){ ...