validate HTML form data client-side with JavaScript in 5 minutes



If you have user input saved to a database you better make sure you know exactly what to expect from that input. The way you do that is by using validations to make the user put in the information in the format you need. I’m sure you’ve gotten that invalid email address error at some point.

That’s because you need to enter your email in a certain format to pass the validation tests. This extends to regular text boxes as well. That’s why you can’t put your address where the phone number should go. It’s also why you can’t enter a credit card number that doesn’t have the right amount of digits.

index:
00:00:00 – Intro.
00:00:40 – validate HTML form data client-side with JavaScript.

spark Fremworks link: https://github.com/reja-e-rabbi/spark
example link: https://github.com/reja-e-rabbi/valid

Why it’s important?
You need form validation as a security measure. Forms are an easy target for hackers because we all know they’re connected to a database somehow. Letting people put whatever they want into your form opens you up to SQL injection attacks as a start and it can get way more advanced than that.

Besides saving you from hackers, form validation also saves you from users. People do some weird stuff man. Somebody could crash your website by putting a ridiculous value into your form just because they felt like it.

Form validation is important for way more reasons than these, but these are the two that I’ve seen destroy projects.

How does it work?
Thankfully, form validation isn’t super hard. There are tons of great libraries out there and most of the frameworks, both back and front end have some kind of built-in validation. It’s really just a bunch of checks.

Is the phone number an actual number? Does the address have the format you expect and is it a real location? Did the user put info in all of the fields you need? You’re making sure that you answer all of these little questions get handled.

Honestly, you can probably get away with some if-else statements, switch statements, and a few regular expressions if you need some really basic validation. But the validation rabbit hole goes as deep as you’re willing to dig.

#javascript #form #validation