- This topic is empty.
June 3, 2014 at 9:42 am #171666
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.
Here is my codepen :
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.
Edit: It looks like CodePen updated some settings. They never displayed like this for me before.June 3, 2014 at 1:31 pm #171699
I 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:
You 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 #171857
Well 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 functionJune 4, 2014 at 2:39 pm #171861
You could then add an event listener to the formElem in place of the onsubmit attribute so you can handle the event within your script.
This function prevents the default event action (i.e. submit) if validate() returns false.June 4, 2014 at 3:32 pm #171866
You 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.
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 #171879
I will try this out.