The function Joi.validate is not defined at this time

I am currently working on creating a validation function for user input

async function validateUserInput(user) {
  const schema = Joi.object({
      password: Joi.string().pattern((new RegExp('^[a-zA-Z0-9]{3,30}$'))),
      repeat_password: Joi.any().equal(Joi.ref('password')).required().messages({ 'any.only': '{{#label}} does not match' }),
      email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'dk']}})
    });
    try {
        const value = await schema.validateAsync((user));
    } catch (err) {
        console.log(err)
    }
  }


However, I am encountering an issue with the repeat_password field,

firstname: 'Mette ',
    lastname: 'Nielsen',
    age: "'35'",
    gender: 'female',
    about: 'I like to go and watch movies',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf1f9e8e8f9f2f5f9f0eff9f2dcaeafaea8a9b2fbfdfbfd">[email protected]</a>',
    password: 'metteNielsen123',
    repeat_password: 'mette',
    likes: 'Shopping, going to the mall, cities',
    dislikes: 'rap musik, events, poor people'

Answer №1

When it comes to validating users, it's important to handle the process correctly.

async function validateUser(user) {
    const schema = Joi.object({
        password: Joi.string().pattern((new RegExp('^[a-zA-Z0-9]{3,30}$'))),
        repeat_password: Joi.any().equal(Joi.ref('password')).required().messages({ 
        'any.only': '{{#label}} does not match' }),
        email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: 
        ['com','dk']}})
     });
     try {
         const value = await schema.validateAsync((user));
     } catch (err) {
         console.log(err)
     }
 }

One way to approach validation is by following this technique:

async function validateUser(user) {
    const schema = Joi.object({
        password: Joi.string().pattern((new RegExp('^[a-zA-Z0-9]{3,30}$'))),
        repeat_password: Joi.any().equal(Joi.ref('password')).required().messages({ 
        'any.only': '{{#label}} does not match' }),
        email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: 
        ['com','dk']}})
     });
     const {error, value} = schema.validate(user)
     // To verify data correctness, check if there are no errors:
     if (!error) {
     // Everything looks good
     } else {
         // You can add a customized error message here
     }
 }

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 best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

JavaScript code for displaying div elements

How can I use script code to show different divs when a button is clicked? This is my current progress: ''' <head> <style> #div-1, #div-2, #div-3{ display: none; width: 100%; padding: ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

Timeout error for WebSocket connection on JavaScript client

My first attempt at using websockets is not going as planned. Since my IP address changes frequently, I decided to make the following websocket call on the server-side: $echo = new echoServer("myurl.com","9000"); On the client-side, I'm making the f ...

Shutting down a filtered v-treeview node becomes sluggish when operating with a large number of items

My v-treeview has a node with approximately 2000 children, and I am in need of applying a filter to it. However, the current issue is that opening the node takes around 3 seconds, while closing it takes about 15 seconds, which is completely unacceptable. ...

Harnessing the Power of Script Loader in Your webpack.config.json File

I'm taking my first steps into the webpack world with Vue.js and vueify for ES6 modules. I've run into a challenge when it comes to loading third-party jQuery plugins. I've successfully used the ProvidePlugin to load jQuery. plugins: [ ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

What is the best way to display the weather information for specific coordinates in ReactJS?

I've been working on a code that retrieves farm details based on longitude and latitude. My goal now is to fetch the weather information for that specific farm using openweathermap However, each time I attempt to do so, an error message {cod: '4 ...

Return the information from Node.js to the JavaScript on the client side

My goal is to establish a fetch connection from client-side JS to the server Node.JS. When a person clicks on a button in HTML, it triggers a search in the MongoDB database on the server side. Once the element is found, I am unsure how to send that informa ...

Passing events from a grandchild component up to its grandparent component in VueJS 2.0

Vue.js 2.0 appears to have a limitation where events cannot be emitted directly from a grand child component to its grand parent. Vue.component('parent', { template: '<div>I am the parent - {{ action }} <child @eventtriggered="pe ...

Bootstrap Datepicker allows you to set a maxdate of 2 days from the initial date selected

Imagine this scenario: when I choose a date for Check-In on May 10th, I want the Check-Out section to automatically show May 10th selected as well, with the following 2 days available and the rest disabled. If you're looking for documentation, you ca ...

What is the correct way to serve JSON files with appropriate MIME type and avoid using text/plain?

My attempts to utilize a manifest.json file have been unsuccessful due to it refusing to work unless the type is set to application/json. The setup includes an nginx server running node/express. I placed the manifest.json in the public folder, but the se ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Managing various dropdown select options in pure JavaScript

Consider the select element provided below: <select multiple="multiple"> <option value="car">car</option> <option value="scooter">scooter</option> <option value="bus">bus</option> </select> I ...

Executing a function within the constructor in Angular 2/IONIC 2

I am new to Angular 2 and I have a question regarding invoking a child method from the current constructor. Is it possible to call the getPosition method from the constructor? I attempted to do so, but encountered an exception stating "getPosition is not ...

How can I trigger an API call 30 seconds after my React Native app switches to the background?

Seeking assistance with my React Native app: I am trying to make an API call 30 seconds after the app goes into the background. I am using AppState from react-native to detect when the app goes into the background, but I'm not receiving any callback a ...

Is there a way to bypass a route and go straight back to the middleware (static) in node.js and express

As I develop my node.js server using express, I want to ensure that the route middleware is executed before the static middleware. This allows me to have complete control over the request and response before serving any static content. In addition, I have ...

Tips for Testing an Ajax jQuery Function Within the document.ready Event

I am in the process of developing a script that utilizes $.ajax to make requests for a json api. My goal is to create unit tests that can verify the results received from the ajax request. For instance, I expect the returned JSON object to contain "items" ...