Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Input verification on front-end or backend (using Express)?

Hello Treehouse community,

I'm working on a little site that will take both a URL and a phone number and send a POST request with the information to an Express backend.

I could send a separate POST request for both the URL and the phone number, and then send a response based upon if the input is valid or not.

However, I'm wondering if it'd be better (or a best practice) to do the validation on the front-end outside of Express. That way I'd only have to send a single POST request with the URL and number.

Any thoughts would be greatly appreciated. Hopefully this makes sense. If you have any questions or need more validation on something, let me know.

Here's a little flow chart I put together that will hopefully make things clear: Flow Chart

Thank you so much!

-Brandon

2 Answers

Hi Brandon,

It is generally recommended to do validation on both. However, it can vary on situation as well. From your diagram, are users only able to enter a phone number if the url is valid? Or can they enter a phone number before entering a url?

If they need to enter a url first, what I would do is to have client side logic first check if the url is valid. If it is then with client side logic check if the phone number is valid. If both are valid they send a post request with both url and phone number in the body. On your express server you check again if both of them are valid. If one of them is invalid respond with an error. That way you make sure your server is still doing what it is supposed to even if a malicious user bypasses your javascript client logic

Stuart Wright
Stuart Wright
41,118 Points

I'm not familiar with Express, but what I'm about to say applies to any web application regardless of language/framework:

You should always validate user inputs on the backend, even if you also do some frontend validation. Frontend validation is easy to bypass. There is no harm in including both - frontend validation can lead to a better user experience, as the user doesn't have to wait on a response from the server to tell them that their input is invalid, but it cannot be relied on as your only validation.