473,837 Members | 1,577 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to exit a form validation function so that the form isn'tsubmitted

HI,

Just a warning, I'm a javascript neophyte. I'm writing a function to
validate the contents of a form on a web page I'm developing. Since
I'm a neophyte, this function is quite simple at this time (in fact, I
don't even know if it totally works, I'm still debugging). However,
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be). Basically, this is
what I've got (without all of the form tags):

in the <headsection of the page:
<script type="text/javascript">
function CheckFormValues () {
var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
if(nullsPresent ) {
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
return;
}

npf.submit();
}
</script>

Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />
What do I need to have in the function to make this function exit so
the user fills in the null strings and then re-submits? As you can
see, I tried a "return;" before the call to nfp.submit(), but that
didn't work. It still submitted the data to the DB.

Thanks,
Andy
Nov 17 '08 #1
13 3618
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.
No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
...
function CheckFormValues () {
(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {
(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
(Is a single space considered valid input?)
Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />
(That's not really a submit button (type="submit") ).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues ()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById( ) call:

function CheckFormValues (npr) { ...
..
<input ... onclick="return CheckFormValues (this.form)" ...>

HTH.
- Conrad
Nov 17 '08 #2
"Andrew Falanga" <af******@gmail .comwrote in message
news:5a******** *************** ***********@u18 g2000pro.google groups.com...
HI,

Just a warning, I'm a javascript neophyte. I'm writing a function to
validate the contents of a form on a web page I'm developing. Since
I'm a neophyte, this function is quite simple at this time (in fact, I
don't even know if it totally works, I'm still debugging). However,
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be). Basically, this is
what I've got (without all of the form tags):

in the <headsection of the page:
<script type="text/javascript">
function CheckFormValues () {
var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
if(nullsPresent ) {
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
return;
}

npf.submit();
}
</script>

Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />
What do I need to have in the function to make this function exit so
the user fills in the null strings and then re-submits? As you can
see, I tried a "return;" before the call to nfp.submit(), but that
didn't work. It still submitted the data to the DB.

Thanks,
Andy
Hi Andrew

No problem to me. I have learnt how to use JS, but as a programmer I never
did come to grips with object oriented languages, so I am still learning

I thought about confirm and prompt boxes refer:
http://www.w3schools.com/js/js_examples_3.asp Window Object

But, maybe you could try (not tested)
<script type="text/javascript">
var npf = document.getEle mentById("NewPa tientForm"); // npf is global
function CheckFormValues () {
var nullsPresent = false;
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
return nullsPresent;
}

if (CheckFormValue s()) { // function returned true
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
CheckFormValues ();
}
else // OK
npf.submit();
</script>

The function might even work like this
function CheckFormValues () {
for(var i=0; i < npf.length; i++) {
if ( npf.elements[i].nodeType == "textarea" && npf.elements[i].value
== "" )
return true;
}
return false;
}

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
Nov 17 '08 #3
What he said.

That is, I gave a solution which should work, with Conrad's points added

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
"Conrad Lender" <cr******@yahoo .comwrote in message
news:eu******** *************** *******@superne ws.com...
On 2008-11-17 01:49, Andrew Falanga wrote:
>Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>function CheckFormValues () {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
> var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
> if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
>Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />

(That's not really a submit button (type="submit") ).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues ()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById( ) call:

function CheckFormValues (npr) { ...
..
<input ... onclick="return CheckFormValues (this.form)" ...>

HTH.
- Conrad

Nov 17 '08 #4
On Nov 17, 11:26*am, Conrad Lender <crlen...@yahoo .comwrote:
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
function CheckFormValues () {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
* *var nullsPresent = false;
* *var npf = document.getEle mentById("NewPa tientForm");
* *for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
* for (var i = 0, len = npf.length; i < len; i++)
)
* * * if(npf.elements[i].nodeType == "textarea")
* * * * *continue;
* * * if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />
This is the key to the OP's issues. Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit").

Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.

Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.

e.g.

<script ...>
function CheckFormValues () {
var passed = true;

// do tests, set passed to false if any fail

return passed;
}
</script>

<form ... onsubmit="retur n CheckFormValues ();" ...>
<!-- form controls ... -->
<input type="submit" ...>
</form>

(That's not really a submit button (type="submit") ).

You can avoid the default action of the button like this:

* <input type="submit" onclick="return CheckFormValues ()" ...>
But it's not the button's default action that needs to be avoided,
it's the form's sumbit that needs to be cancelled.

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById( ) call:

* function CheckFormValues (npr) { ...
* ..
* <input ... onclick="return CheckFormValues (this.form)" ...>
And if the form is submitted some other way (e.g. pressing enter in
IE) the validation function won't be called. Use the form's onsubmit
handler.
--
Rob
Nov 17 '08 #5
Actually come to think of it, my solution won't work, for quite a few
reasons. So using Conrad's changes, it is probably more like this

<script type="text/javascript">
function CheckFormValues (npf) { ...
for(var i=0, len= npf.length ; i < len; i++) {
if ( npf.elements[i].nodeType == "textarea"
&& npf.elements[i].value == "" ) // or other null values ??
return false;
}
return true;
}
</script>

<input type="submit" onclick="return CheckFormValues (this.form)" ...>
The function will return true if no nulls (however defined) are found; false
if there are. On the assumption that false is the value that cancels the
submit action, this should work.

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org

"Trevor Lawrence" <Trevor L.@Canberrawrot e in message
news:ne******** ************@ne ws.grapevine.co m.au...
What he said.

That is, I gave a solution which should work, with Conrad's points added

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
"Conrad Lender" <cr******@yahoo .comwrote in message
news:eu******** *************** *******@superne ws.com...
>On 2008-11-17 01:49, Andrew Falanga wrote:
>>Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
>>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>>function CheckFormValues () {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
>> var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
>> if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
>>Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />

(That's not really a submit button (type="submit") ).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues ()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById( ) call:

function CheckFormValues (npr) { ...
..
<input ... onclick="return CheckFormValues (this.form)" ...>

HTH.
- Conrad
Nov 17 '08 #6
Conrad Lender meinte:
On 2008-11-17 01:49, Andrew Falanga wrote:
> var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
Erm... gEBI() returns one *element*. Impossible to iterate through that.

Gregor
Nov 17 '08 #7
RobG wrote:
On Nov 17, 11:26 am, Conrad Lender <crlen...@yahoo .comwrote:
>On 2008-11-17 01:49, Andrew Falanga wrote:
>>Just a warning, I'm a javascript neophyte.
No problem. I've put some recommendations in parentheses.
>>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>>function CheckFormValues () {
(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
>> var nullsPresent = false;
var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {
(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
>> if(npf.elements[i].nodeType == "textarea")
continue;
if(npf.elements[i].value == "") {
(Is a single space considered valid input?)
>>Then, the submit button (in the form tags):
<input type=button onClick="CheckF ormValues()" style="height:4 0px;font-
size:18px;" value="Submit New Patient" />

This is the key to the OP's issues. Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit").

Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.

Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.
That's one way.

I did this another way.

The submit button isn't a submit button, its a generic button that
calls, on click, a javascript function that does the following
- validates.
- if validation fails, pops up an alert
- if validations pases, executes document.forms[0].submit();

In case its useful, here is the relevant stuff

*** style sheet *************** **************

..button1

{
background-image: url("../Images/Button2.gif");
background-repeat: no-repeat;
background-position: center center;
text-align: center;
cursor:default;
font-size: 9px;
color: #000000;
vertical-align: middle;
}
..hotbutton

{
cursor: pointer;
background-image: url("../Images/Button2.gif");
background-repeat: no-repeat;
background-position: center center;
color: #ff2020;
font-size: 9px;
text-align: center;
vertical-align: middle;
}

..button2
{
background-image: url("../Images/Button1.gif"); // a bit cute. This is
an image of a button that has been pressed :-)
background-repeat: no-repeat;
background-position: center center;
color: green;
cursor:default;
font-size: 9px;
text-align: center;
vertical-align: middle;
}

*************** *************** ******
These allow me to draw little button images to any shape and style I
want. I use ones with drop shadow created as transparent background
gifs..These move the cursor to pointer type when the mouse moves over..

Here is a typical button drawing HTML fragment:-
*** HTML *************** ************

<div class="button1"
style="position : absolute; top: 48px; left: 200px; width: 125px; height:
35px"
id="newproject " onmouseover="th is.className='h otbutton'"
onmouseout="thi s.className='bu tton1'"
onclick="this.c lassName='butto n2';newproject( );" >
<div style="position : absolute; font-weight: bold;
text-align: center; width:95px; left:15px; top:8px">
NEW PROJECT</div>
</div>

*************** *************** *************** *******
The inner div is to place the lettering exactly over the button center
for nice appearance..val ues depend on the pixel height of the button gif.

Then the onclick function:-
*************** *************** *************** *******
<script>
function newproject()
{
// put your validation code here.
if (valid)
document.forms[0].submit();
else alert ("you fsked up");
}
</script>
*************** *************** *************** *******
So, no actual submit button is ever used. Ok this has a problem on that
it depends utterly on the browser supporting javascript, but frankly, if
they dont. tell them that this page needs it and if they can't be arsed
to upgrade to a browser that does, they can fsck themselves.

once you get to the point where javascript is needed to get the
functionality you want, you have to ask the question of why bother with
most of the ugly form elements in the first place?

You can very easily make your own input elements of type checkbox,
radio, submit and select/option. The only three I haven't yet faked are
text, textarea and file..

Nov 17 '08 #8
On 2008-11-17 11:47, Gregor Kofler wrote:
>On 2008-11-17 01:49, Andrew Falanga wrote:
>> var npf = document.getEle mentById("NewPa tientForm");
for(var i=0; i < npf.length; i++) {
....
Erm... gEBI() returns one *element*. Impossible to iterate through that.
Try it :-)

npf.elements would be better style, but form nodes do have a length
property and numeric indices.
- Conrad
Nov 17 '08 #9
On Nov 17, 8:47*pm, The Natural Philosopher <a...@b.cwrot e:
RobG wrote:
[...]
This is the key to the OP's issues. *Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit"). .
Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.
Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.

That's one way.
It's often recommended here as the best way.

I did this another way.

The submit button isn't a submit button, its a generic button that
calls, on click, a javascript function that does the following
- validates.
If the button is clicked, what if the user is using IE and submits the
form by pressing enter while the focus is on some other control?

- if validation fails, pops up an alert
A really annoying way to tell users their input is not what you
expect.

- if validations pases, executes document.forms[0].submit();
So if the user submits the form by means other than the button,
validation doesn't run. And if javascript is disabled or not
functioning, the user can't submit the form at all.

I don't understand the need to replace native features that are
perfectly functional with problematic scripts. Javascript is
available to enhance the UI, not make it dysfunctional.

[...]
So, no actual submit button is ever used. Ok this has a problem on that
it depends utterly on the browser supporting javascript,
And the user having scripting turned on, and the script executing
correctly, and the user using the button to submit the form...

but frankly, if
they dont. tell them that this page needs it and if they can't be arsed
to upgrade to a browser that does, they can fsck themselves.
So you lose say 5% of visitors for the sake of a mass of CSS, images
and script to replace a single HTML element. Not a particularly good
trade-off.

once you get to the point where javascript is needed to get the
functionality you want, you have to ask the question of why bother with
most of the ugly form elements in the first place?

You can very easily make your own input elements of type checkbox,
radio, submit and select/option. The only three I haven't yet faked are
text, textarea and file..
That is completely the wrong approach. If you are keen to build
brittle, slow and poorly functioning web sites, go for it. But if I
were to stumble across such a site, I wouldn't be there for very long.
--
Rob
Nov 17 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3044
by: peebrain | last post by:
I understand how to validate form data when a form is submitted to 'self' (ie. action="$_SERVER_"). In this case you simply validate before processing. However, what if submitting the form to another page (ie. action="someotherpage.php"). You could validate the form data on the new page but it makes more sense to validate first before submitting, plus if there are errors, then you have to send the user back to the first page. There must be...
9
4184
by: julie.siebel | last post by:
Hello all! As embarrassing as it is to admit this, I've been designing db driven websites using javascript and vbscript for about 6-7 years now, and I am *horrible* at form validation. To be honest I usually hire someone to do it for me, grab predone scripts and kind of hack out the parts that I need, or just do very minimal validation (e.g. this is numeric, this is alpha-numeric, etc.)
7
7002
by: h7qvnk7q001 | last post by:
I'm trying to implement a simple server-side form validation (No Javascript). If the user submits a form with errors, I want to redisplay the same form with the errors highlighted. Once the form is correct I need to submit to another page that uses the form data. I first tried making the form submit action= field point to the same file. When the form was correct, I tried loading the next page by using <META http-equiv refresh>. But...
27
4778
by: Chris | last post by:
Hi, I have a form for uploading documents and inserting the data into a mysql db. I would like to validate the form. I have tried a couple of Javascript form validation functions, but it appears that the data goes straight to the processing page, rather than the javascript seeing if data is missing and popping up an alert. I thought it may be because much of the form is populated with data from the db (lists, etc.), but when I leave...
7
3626
ak1dnar
by: ak1dnar | last post by:
Hi, I got this scripts from this URL There is Error when i submit the form. Line: 54 Error: 'document.getElementbyID(....)' is null or not an object What is this error. Complete Files
3
2169
by: dirk | last post by:
Hi, Being new coding in phpI have a question concerning server side form validation. In a php script I check if a form is correctly filled in. Now I want that the page containing the forms is represented agian so that the user can fill in a correct value. The other forms that a correctly filled in should be
2
1897
by: obtrs | last post by:
im using java script for form validation.. here is the code <script type="text/JavaScript"> function validate_required(field,alerttxt) { with (field)
1
3338
by: metalforever | last post by:
How do you redirect a form after submit(form sends email) ? This is pretty urgent for me. I have included the code in a pastebin. http://pastebin.org/249014 process_form sends the email. The redirect is easily findable. Thanks.
2
1647
by: munkee | last post by:
Hi all, Basically I have been using form validation incorrectly. Partly because of laziness which I now feel is going to really bite me back if I dont get it sorted. On all of my forms I have a save button. Simply because it is often easier to explain to people just click save and it will save the record than it is for them to grasp the idea that access doesnt need a record to be "saved" from a button. In the click event of this save...
0
10902
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10583
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9420
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7013
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5680
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.