Forum Moderators: open

Message Too Old, No Replies

Need to combine 2 scripts

for form validation

         

Adam_C

12:16 pm on May 12, 2004 (gmt 0)

10+ Year Member



I need to use the following 2 scripts for validating various elements of a form, but can't call both in the onsubmit of the <form> tag.

Help much appreciated!

<script type="text/javascript">
function validate(f){
if((f.telephone.value.length<1)&&(f.daytime.value.length<1)&&(f.mobile.value.length<1)){
alert('Please fill at least one phone no');
return false;
}

}
</script>

and

<script type="text/javascript">
function checkPw(form) {
email1 = form.email1.value;
email2 = form.email2.value;

if (email1!= email2) {
alert ("\nYou did not enter the same email address twice. Please re-enter your email address.")
return false;
}
else return true;
}
</script>

Bernard Marx

12:57 pm on May 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Combined in the same function (untested):

[pre]
String.prototype.trim = function(){ return this.replace(/^\s+/,'').replace(/\s+$/,''); }

function validate(f)
{
var complete = true
var message = ''
if(
!f.telephone.value.trim() &&
!f.daytime.value.trim() &&
!f.mobile.value.trim()
)
{
message [red]+[/red]= 'Please fill at least one phone no\n\n'
complete = false;
}

if(f.email1.value.trim()!=f.email2.value.trim())
{
message [red]+[/red]= 'You did not enter the same email address twice.\nPlease re-enter your email address.'
complete = false
}

if(!complete)
alert(message)
return complete;
}
[/pre]

I have included a String::trim method. Might as well remove whitespace.

creative craig

3:09 pm on May 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Adam's not in the office at the moment, but I have slightly modified the code:


if(!complete) {
alert(message)
return false }
}

Its all working now :)

Cheers Bernard.

Craig

Bernard Marx

3:37 pm on May 12, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Nice, Craig. When Adam gets back, would you be so kind as to inform him that I'm not so sure why it wasn't working in the first place.
complete
is
true
unless set to
false
.

At the bottom, if

false
, the alert is done, and
false
is returned, if
true
, the alert isn't done, and
true
is returned. So..

[pre]
if(!complete)
alert(message)[red];[/red]
return complete;
[/pre]

is synonymous with
[pre]
if(!complete) {
alert(message)
return false }
}
return true
[/pre]

I think that the problem was that I was lazy, and left out the ;
- and copy'n'paste removed the line break.