/    Sign up×
Community /Pin to ProfileBookmark

The JavaScript tutorial I was reading acted like all you had to do to validate your form was to alert the users of an error when they clicked the submit button. Is that all there is to it? Don’t you need some way to cancel the post method in the form?

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@ripcurlksmJun 13.2008 — I dont think so Joe because the form wont submit or even post until javascript allows for it to be submitted.

Here is another snippet of code that might help you. Just copy and paste it into a new HTML file, save it, then preview it in a browser: (ps- it only validates if the field is left blank or not. It does not validate email addresses or anything, but hopefully it helps you)
<i>
</i>&lt;script language="JavaScript"&gt;

function checkFieldsProfileUpdate() {
missinginfo = "";

if (document.companyUpdate.company.value == "") {
missinginfo += "n - 'Company Name' was left blank! n";
}
if (document.companyUpdate.email.value == "") {
missinginfo += "n - 'Email' Must be filled in!";
}


if (missinginfo != "") {
missinginfo ="You did not fill in all required fields: n___________________________________________________n" +
missinginfo + "n___________________________________________________" +
"n n Please re-enter and submit again!";
alert(missinginfo);
return false;
}
else return true;
}

&lt;/script&gt;

&lt;form name="companyUpdate" action="" method="post" enctype="multipart/form-data" onSubmit="return checkFieldsProfileUpdate();"&gt;
company
&lt;label&gt;
&lt;input type="text" name="company" id="company"&gt;
&lt;/label&gt;
&lt;br&gt;
email
&lt;label&gt;
&lt;input type="text" name="email" id="email"&gt;
&lt;/label&gt;&lt;br&gt;
&lt;input name="Submit" value="Submit" type="submit"&gt;
&lt;/form&gt;
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 13.2008 — I'm having some trouble with it, so if someone could point me in the right direction, I would greatly appreciate it.'

Here is my JavaScript code:
[CODE]function formIsEmpty {

// assign the form fields to variables

var title = document.getElementById('title');
var url = document.getElementById('url');
var button = document.getElementById('button');
var email = document.getElementById('email');

// if the any of the fields are empty, alert the user

if(title == " ") || (url == " ") || (button == " ") || (email == " ") {

alert('All fields are required!');

}
}[/CODE]


And here is my form:
[code=html]<form id="AffiliateForm" method="post" action=" " onSubmit="formIsEmpty();">
<input name="title" id="title" type="text" class="formbox">
<input name="url" id="url" type="text" class="formbox">
<input name="button" id="button" type="text" class="formbox">
<input name="email" id="email" type="text" class="formbox">
<input name="send" id="send" type="submit" value="Send Owl">[/code]


I submit the form and it acts as though I never added any JavaScript to the page.
Copy linkTweet thisAlerts:
@mainenotarynetJun 14.2008 — Look at your code carefully:
if(title == " ") || (url == " ") || (button == " ") || (email == " ")

you have spaces between your quotes, if you are checking for unfilled values , a space IS a value and will never be true if a field is NULL

try your current code by placing a space (nothing else, just one space in a required field and your code should work.

then replace the line above with if(title == "") || (url == "") || (button == "") || (email == "")
and that should fix your code not working like you want.
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 14.2008 — Tried that, and it still does the same thing:o
Copy linkTweet thisAlerts:
@mainenotarynetJun 15.2008 — Didi you try:
if(title == NULL) || (url == NULL) || (button == NULL) || (email == NULL)

another question-- is your if statement in a php page? if so try:
if(empty($_POST['title']) || empty($_POST['url']) || empty($_POST['button']) || empty($_POST['email']))

or set up values before the if statement like so:
$title=$_POST['title']
one for each variable and then rewrite the if statement as:
if(empty($title) || empty($url) || empty($button) || empty($email))

variables in a form when passed to a php page are set in the $_Post array and all php variables start with the $ character

hope this helps
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 15.2008 — Well, I got the JavaScript part to work (though it took a lot of modifications to my code, so it looks much different than it used to). But the thing now is, even when the alert pops up telling your user that he needs to fill in all fields, after you exit out of the alert, it still attempts to send the message. Is there anyway to cancel out the post method with JavaScript?

P.S. And yes, I'm using PHP to process the form.
Copy linkTweet thisAlerts:
@mainenotarynetJun 16.2008 — You say your code looks different now? we need to see it in order to see what is incorrect, however - shot in the dark here,

in the formisempty() (your original code after the alert it exits without returning anything.

you say it still submits the form?

using your original code replace with: function formIsEmpty {

// assign the form fields to variables

var title = document.getElementById('title');
var url = document.getElementById('url');
var button = document.getElementById('button');
var email = document.getElementById('email');

// if the any of the fields are empty, alert the user

if(title == " ") || (url == " ") || (button == " ") || (email == " ") {
alert('All fields are required!');
return false; <br/>
} else {
return true
}
}


what this does is returns if the form should be submitted at all yet.

in your posting routine enclose it in an if statement
if (formisempty()) { // process data
... }


with no else only when all field are filled will it get posted

anyone else have ideas? The more the merrier as I am limited in my knowledge as well

Hope this helps

Maine Notary Net
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 16.2008 — That last bit of code you said to put in. You mean put it, like, before the PHP code starts?
Copy linkTweet thisAlerts:
@mainenotarynetJun 16.2008 — You said your codse had changed since original post and that even if the alert that the form was not completely filled in it was still submitting incomplete info. You aslo said you were using PHP to process the form.

surround that entire process with the if statement like:
&lt;?php
if formisempty() {
//do the processing
}
?&gt;


so to answer your question not befor the php starts but as the first statement of the php code.

post your new code that works incorrectly and I can probably tell you where exactly to put it.

Maine Notary Net
Copy linkTweet thisAlerts:
@Declan1991Jun 16.2008 — To have JavaScript validation, you MUST MAKE SURE that you validate on the server too. Turning off JavaScript is very easy. Here is a sample code.&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;style type="text/css"&gt;

&lt;/style&gt;
&lt;script type="text/javascript"&gt;
function formIsEmpty(f){
var r = true,e = document.getElementById("error");
removeChildren(e);
if (f.title.value==="") {
e.appendChild(createP("Title Field is empty."));
r=false;
}
if (f.url.value==="") {
e.appendChild(createP("URL Field is empty."));
r=false;
}
if (f.button.value==="") {
e.appendChild(createP("Button Field is empty."));
r=false;
}
if (f.email.value==="") {
e.appendChild(createP("Email Field is empty."));
r=false;
}
if (!/^w+(.w+)?@w+(.w+)?.w{2,3}$/.test(f.email.value)) {
e.appendChild(createP("Email is in an invalid form."));
r=false;
}
return r;
}
function createP(m) {
var t = document.createElement("p");
t.appendChild(document.createTextNode(m));
return t;
}
function removeChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;form name="AffiliateForm" method="post" action="" onSubmit="return formIsEmpty(this);"&gt;
Title: &lt;input name="title" type="text" class="formbox"&gt;&lt;br&gt;
URL: &lt;input name="url" type="text" class="formbox"&gt;&lt;br&gt;
Button: &lt;input name="button" type="text" class="formbox"&gt;&lt;br&gt;
Email: &lt;input name="email" type="text" class="formbox"&gt;&lt;br&gt;
&lt;input name="send" type="submit" value="Send Owl"&gt;
&lt;div id="error"&gt;

&lt;/div&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

If you tell me what type of characters etc. you want in the other fields, I'll write validation rules for them too. You MUST validate on the server too. This is only to facilitate your users by not having to refresh the page to know that a field has an invalid value.
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 17.2008 — I do validate on the server side with PHP, so I'm not having any problems with that. I've never really worked with JavaScript before, so that's why I'm asking all of this.

My PHP code that processes the form:
[code=php]<?php // process the form


if (array_key_exists('send', $_POST) and !empty($_POST['send'])) {
$to = '[email protected]' ;
$subject = 'Rebirth Affiliation Request' ;

// list required and expected fields
$expected = array('title', 'url', 'button', 'email');
// set the required fields
$required = array('title', 'url', 'button', 'email');

// create an empty array for missing fields
$missing = array();


// assume there is nothing to suspect
$suspect = false;

// create a pattern to locate suspect phrases
$pattern = '/Content-Type:|Bcc:|Cc:/i';

// process post variables
foreach ($_POST as $key => $value) {
// assign to temporary variable and strip whitespace if not an array
$temp = is_array($value) ? $value : trim($value);
// if empty and required, add to missing array
if (empty($temp) && in_array($key, $required)) {
array_push($missing, $key);
}
// otherwise, assign to a variable of the same name as $key
elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}

// go ahead only if all required fields OK
if (empty($missing)) {

$title = $_POST['title'];
$url = $_POST['url'];
$button = $_POST['button'];
$email = $_POST['email'];

// time to build the message!
$message = "Title: $titlenn";
$message .= "URL: $urlnn";
$message .= "Button: $buttonnn";
$message .= "Email: $emailnn";

/* Rebirth has fallen victim to
viagra and cialis spammers. As
to why, I do not know. This next
bit of code is used in order to
keep them from annoying the crap
out of me. */

$lowerCase = strtolower($message);

if (strpos($lowerCase, "viagra") || strpos($lowerCase, "cialis")) {

// *grins* let's send them to a special page
header("Location: http://www.uhrebirth.com/not_so_fast/male_meds.html");

exit;
}
else {

// time to send the message
$mailSent = mail($to, $subject, $message);

}

}
if ($mailSent) {
// missing is no longer needed
unset($missing);
}
}

?>[/code]


And my JavaScript code:
[CODE]<!--
function formIsEmpty() {





// if the any of the fields are empty, alert the user

if(AffiliateForm.title.value.length == 0) {
alert('All fields are required!');
return true;
}

return false;


}
//-->

/* NOTE: The reason I only have it checking for one field
is because so far I've just been testing the script. Once I
get everything working like it's supposed to, I'll add the
other fields in. */[/CODE]
×

Success!

Help @Joseph_Witchard spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...