Home › Forums › JavaScript › Help with form validation
- This topic is empty.
-
AuthorPosts
-
June 3, 2014 at 9:42 am #171666cyclinggParticipant
I am working on validating a form I created and just get more confused the more I work on it.
I need to validate required fields for empty fields. I need to validate some fields for alpha characters. I need to validate the phone number to accept only integers and the credit card field. I need to validate email for the “@” and “.”.
At the moment I am working on the validating for empty fields and it is not working.
All examples I find online are for individual field tests and not for a full form. So, when I try to use some code for my whole form, I fail big time.The way I wrote out my .js so far is based on my notes from the online pdf only course I am taking at my local school. It is intro to javaScript.
Here is my codepen :
http://codepen.io/cyclingg/pen/sIqHl
Am I far off base? Are there any good easy to follow tutorials online? The ones I have found get me confused or it is only using one field examples. I understand those when I read them; but, cannot get them to work when I try on my form.
Thanks.
Edit: It looks like CodePen updated some settings. They never displayed like this for me before.
June 3, 2014 at 1:31 pm #171699cyclinggParticipantI did some more Google searches and came up with a solution for my text fields. I still need to work on the drop-down lists.
I was wondering if there is a way to shorten this or not? I am not using an alert for the messages. I am using “inner.HTML” to place the message in my form.
Here is the update CodePen:
http://codepen.io/cyclingg/pen/knpEmYou need to hit the Edit button to see the code. I think codePen changed this from the last time I used it.
June 4, 2014 at 2:13 pm #171857MawahaParticipantWell the first thing you could do is reduce the repetition of your validation checks and simply send the appropriate error message to your error handler function
June 4, 2014 at 2:39 pm #171861MawahaParticipantYou could then add an event listener to the formElem in place of the onsubmit attribute so you can handle the event within your script.
http://codepen.io/mawaha/pen/vbrmn
This function prevents the default event action (i.e. submit) if validate() returns false.
June 4, 2014 at 3:32 pm #171866MawahaParticipantYou could then pass the event object to your validate(event) function and use it to extract the text input types and pass each to a validateEmpty() function.
http://codepen.io/mawaha/pen/oBeFf
Then you can remove all the repetitive if statements.
A good rule of thumb is if you have to repeat a task 2 or more times then it may be best to abstract that functionality to a function of its’ own.
This is usually referred to as keeping your code DRY. As in Don’t Repeat Yourself :)
June 4, 2014 at 5:45 pm #171879cyclinggParticipantI will try this out.
Thanks.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.