1
\$\begingroup\$

I am a beginner to JavaScript and I know about jQuery Validations however I do not want to use a foundation like jQuery just yet.

I am wondering if what I have done its good or if there is another way to do it other then jQuery?

I won't post the html just the JS. It does work by the way! Just wondering if there is a better way!

function validateForm() {
 var userName = document.forms["register"]["username"].value;
 var passWord = document.forms["register"]["password"].value;
 var c_passWord = document.forms["register"]["c_password"].value;
 if (userName == null || userName == "") {
 alert("Your username can not be empty!");
 return false;
 } else if (userName.length < 3) {
 alert("Your username must be atleast 3 characters long!");
 return false;
 }
 if (passWord == null || passWord == "") {
 alert("Your password can not be empty");
 return false;
 } else if (passWord.length < 5) {
 alert("Your password must be more the 5 characters");
 return false;
 }
}
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Mar 3, 2017 at 16:04
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It mostly looks fine. Some things I would change:

var userName = document.forms["register"]["username"].value;
var passWord = document.forms["register"]["password"].value;

I would extract the repetition here to get the form. This makes the code cleaner and makes it simpler if you change the name of the form.

var form = document.forms["register"];
var userName = form["username"].value;
var passWord = form["password"].value;

Here

if (userName == null || userName == "") {

You could just use

if (!userName == null) {

One last thing is that you probably want to check and remove leading and trailing spaces in the user name (and possibly in the password). There is a built in trim method you can use if you're not targeting IE8.

answered Mar 3, 2017 at 18:09
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for the input! Could you give me an example of the trim method? \$\endgroup\$ Commented Mar 3, 2017 at 19:02
  • \$\begingroup\$ Something like userName = userName && userName.trim(); \$\endgroup\$ Commented Mar 3, 2017 at 22:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.