Joi How To Validate Only Some Keys

Joi How To Validate Only Some Keys




🔞 ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻

































Joi How To Validate Only Some Keys

Sign up or log in to customize your list.

more stack exchange communities

company blog


Stack Overflow for Teams
– Start collaborating and sharing organizational knowledge.



Create a free Team
Why Teams?



Asked
3 years, 8 months ago


Modified
2 years, 7 months ago


node.js validation schema hapi.js joi


2,152 4 4 gold badges 28 28 silver badges 38 38 bronze badges




Highest score (default)


Trending (recent votes count more)


Date modified (newest first)


Date created (oldest first)




1,287 13 13 silver badges 18 18 bronze badges


456 1 1 gold badge 7 7 silver badges 14 14 bronze badges


Stack Overflow

Questions
Help



Products

Teams
Advertising
Collectives
Talent



Company

About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us
Cookie Settings
Cookie Policy



Stack Exchange Network



Technology




Culture & recreation




Life & arts




Science




Professional




Business





API





Data






Accept all cookies



Customize settings


Find centralized, trusted content and collaborate around the technologies you use most.
Connect and share knowledge within a single location that is structured and easy to search.
Admin will create users, and while doing so he will enter some random string as a password. When admin edit the existing user, he don't need to enter any password unless he wants to change it. If the admin doesn't enter any password, then the old password will be used.
So i am trying to use .when() to handle this case. When _id exists in the payload (which is possible only when the user exists) , then we should make the password field optional or else password is required.
Joi have a method .when in case of such cases. But for some strange reason it is giving me
as the response of the api, and there is nothing in the server console.
I tried to compare the string length for _id as well instead of exists() and i have also tried
for password key, but still the same issue.
If any one has any kind of idea on this issue, please help me.
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Well, I created a simple test and all conditions are passed according to your requirements.
I believe there is something else in your code occurs that error.
Here is my test code, please take a look.
With the above, Joi will ensure that password is required whenever _id exists
Thanks for contributing an answer to Stack Overflow!

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.9.9.42970


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .




By Size



Enterprise






Teams






Compare all






By Solution



CI/CD & Automation








DevOps








DevSecOps








Case Studies



Customer Stories






Resources










In this repository


All GitHub





In this repository


All GitHub





In this organization


All GitHub





In this repository


All GitHub








Code



Issues



Pull requests



Actions



Security



Insights





bsiddiqui opened this issue
Oct 12, 2015
· 7 comments







bsiddiqui opened this issue
Oct 12, 2015
· 7 comments









support

Questions, discussions, and general support

var user = Joi . object ( { firstName : Joi . string ( ) . required ( ) , lastName : Joi . string ( ) . required ( ) } )
Joi . validate ( { firstName : 'John' } , user )





Marsup




added
the

support

Questions, discussions, and general support
label


Oct 12, 2015







Marsup




self-assigned this


Oct 12, 2015







bsiddiqui




closed this as completed


Oct 12, 2015







lock
bot



locked as resolved and limited conversation to collaborators


Jan 10, 2020





Sign up for free
to subscribe to this conversation on GitHub .
Already have an account?
Sign in .







support

Questions, discussions, and general support











You can’t perform that action at this time.





You signed in with another tab or window. Reload to refresh your session.
You signed out in another tab or window. Reload to refresh your session.


Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Is there a way to only validate the provided keys against those keys in the schema instead of validating against the whole schema?
This will obviously error because lastName is required. I'd like to find a way to only compare the provided keys though.




The text was updated successfully, but these errors were encountered:

@Marsup the problem is that when performing an database insert I want to validate against the whole schema but when performing an update I want to only validate against the keys that are being updated. Ideally I'd like to do this without having two different schemas
Using requiredKeys or optionalKeys should help.
Yeah i thought about doing that but that would require me to be aware of which keys to make optional in a more complex schema. Would you recommend parsing the schemas keys and using that to figure out which keys to make optional?
What kind of complexity are we talking about ? If that involves arrays, it's always messy and you're better off with 2 different schemas (might be some reusable parts), if not you can't manage with those 2 operations.
That sounds good - I'll make it work with those operators where I can and split up the schemas where they can't. Thanks for the help!
I'd recommend having a base schema with the keys that should be required at all times (id, date, ...) and adding the required keys then.

How To Install an Upstream Version of Node.js on Ubuntu 12.04
How To Install And Run A Node.js App On Centos 6.4 64bit
Published on December 12, 2019 · Updated on September 23, 2020
Developer and author at DigitalOcean.
Developer and author at DigitalOcean.
Developer and author at DigitalOcean.
Success! Thank you! Please check your email for further details.
Imagine you are working on an API endpoint to create a new user. User data—such as firstname , lastname , age , and birthdate —will need to be included in the request. A user mistakenly entering their name in as the value for the age field when you are expecting a numeric value would not be desirable. A user typing out their birthday for the birthdate field when you are expecting a particular date format would also not be desirable. You do not want bad data making its way through your application. You can address this with Data Validation .
If you have ever used an ORM (object-relational mapping) when building your Node application—such as Sequelize, Knex, Mongoose (for MongoDB)—you will know that it is possible to set validation constraints for your model schemas. This makes it easier to handle and validate data at the application level before persisting it to the database. When building APIs, the data usually comes from HTTP requests to certain endpoints, and the need may soon arise to be able to validate data at the request level .
In this tutorial, you will learn how we can use the Joi validation module to validate data at the request level. You can learn more about how to use Joi and the supported schema types by checking out the API Reference .
At the end of this tutorial, you should be able to do the following:
To complete this tutorial, you’ll need:
This tutorial was verified with Node v14.2.0, npm v6.14.5, and joi v13.0.2.
For this tutorial, you will pretend that you are building a school portal and you want to create API endpoints:
You will create a REST API for this tutorial using Express to test your Joi schemas.
To begin, open your command line terminal and create a new project directory:
Run the following command to set up a new project:
And install the required dependencies:
Create a new file named app.js in your project root directory to set up the Express app:
Here is a starter setup for the application.
First, require express , morgan , and body-parser :
Next, add morgan logging and body-parser middlewares to the request pipeline of your app:
These middlewares fetch and parse the body of the current HTTP request for application/json and application/x-www-form-urlencoded requests, and make them available in the req.body of the request’s route handling middleware.
Your app.js file is complete for the moment.
From your application setup, you specified that you are fetching your routes from a routes.js file.
Let’s create the file in your project root directory:
Require express and handle requests with a response of "success" and the data in the request:
Next, establish endpoints for people , auth/edit , and fees/pay :
Now, when a POST request hits either of these endpoints, your application will use the genericHandler and send a response.
Finally, add a start script to the scripts section of your package.json file:
Run the app to see what you have so far and that everything is working properly:
You should see a message like: "App running on port 3000" . Make a note of the port number that the service is running on. And leave your application running in the background.
You can test the API endpoints using an application such as Postman.
Note: If this is your first time using Postman, here are some steps on how to use it for this tutorial:
Then click Send to view the response.
Let’s consider a scenario where an administrator is creating a new account for a teacher named “Glad Chinda”.
You will receive this example response:
You will have received a "success" status, and the data you submitted is captured in the response. This verifies that your application is working as expected.
A simplified example may help give you an idea of what you will achieve in later steps.
In this example, you will create validation rules using Joi to validate an email, phone number, and birthday for a request to create a new user. If the validation fails, you send back an error. Otherwise, you return the user data.
Let’s add a test endpoint to the app.js file:
This code adds a new /test endpoint. It defines data from the request body. And it defines schema with Joi rules for email , phone , and birthday .
The constraints for birthday include:
Next, handle passing and failing validation:
This code takes the data and validates it against the schema .
If any of the rules for email , phone , or birthday fail, a 422 error is generated with a status of "error" and a message of "Invalid request data" .
If all of the rules for email , phone , and birthday pass, a response is generated with a status of "success" and a message of "User created successfully" .
Now, you can test the example route.
Start the app again by running the following command from your terminal:
You can use Postman to test the example route POST /test .
You should see something similar to the following response:
Here is a demo video accomplishing this:
You can specify more validation constraints to the base schema to control the kind of values that are considered valid. Since each constraint returns a schema instance, it is possible to chain several constraints together via method chaining to define more specific validation rules.
It is recommended that you create object schemas using Joi.object() or Joi.object().keys() . When using any of these two methods, you can further control the keys that are allowed in the object using some additional constraints, which will not be possible to do using the object literal method.
Sometimes, you may want a value to be either a string or number or something else. This is where alternative schemas come into play. You can define alternative schemas using Joi.alternatives() . It inherits from the any() schema, so constraints like required() can be used with it.
Refer to the API Reference for detailed documentation of all the constraints available to you.
After familiarizing yourself with constraints and schemas in Joi, you can now create the validation schemas for the API routes.
Create a new file named schemas.js in the project route directory:
The /people endpoint will use personDataSchema . In this scenario, an administrator is creating accounts for teachers and students. The API will want an id , type , name , and possibly an age if they are a student.
id : will be a string in UUID v4 format:
type : will either be a string of STUDENT or TEACHER . Validation will accept any case, but will force uppercase() :
age : will either be an integer or a string with a value greater than 6 . And the string can also contain shortened formats of “year” (like “y”, “yr”, and “yrs”):
firstname , lastname , fullname : will be a string of alphabetic characters. Validation will accept any case, but will force uppercase() :
A string of alphabetic characters for firstname and lastname :
If fullname is specified, then firstname and lastname must be ommitted. If firstname is specified, then lastname must also be specified. One of either fullname or firstname must be specified:
Putting it all together, peopleDataSchema will resemble this:
The /auth/edit endpoint will use authDataSchema . In this scenario, a teacher is updating their account’s email and password. The API will want an id , email , password , and confirmPassword .
id : will use the validation defined earlier for personDataSchema .
email : will be a valid email address. Validation will accept any case, but will force lowercase() .
password : will be a string of at least 7 characters:
confirmPassword : will be a string that references password to ensure the two match:
Putting it all together, authDataSchema will resemble this:
The /fees/pay endpoint will use feesDataSchema . In this scenario, a student is submitting their credit card information to pay an amount of money, and the transaction timestamp is also recorded. The API will want an id , amount , cardNumber , and completedAt .
id : will use the validation defined earlier for personDataSchema .
amount : will either be an integer or a floating point number. The value must be a positive number greater than 1 . If a floating point number is given, the precis
Pony Fetish
Fake Agent Cz 18
Xxx Mega Hairy Big Bush Mature Chubby

Report Page