Javascript Validate Form Fields

C

Colin Graham

Hi there,

Im very new to javascript and this is my first bit of javascript
coding. I have to write a validation check for two fields that they
don't contain all the same characters e.g.,

field 1 = 111111 field 2 = 11111111

OR

field 1 = 000000 field 2 = 00000000

my script wants to check to see if this is happening and display an
error message.

I would also be agreatful if anyone could point me towards any
javascript code banks on the web as this would help speed up my
learning.

any help greatly appreciated.

Thanks

Colin
 
R

RobB

Colin said:
Hi there,

Im very new to javascript and this is my first bit of javascript
coding. I have to write a validation check for two fields that they
don't contain all the same characters e.g.,

field 1 = 111111 field 2 = 11111111

OR

field 1 = 000000 field 2 = 00000000

my script wants to check to see if this is happening and display an
error message.

I would also be agreatful if anyone could point me towards any
javascript code banks on the web as this would help speed up my
learning.

any help greatly appreciated.

Thanks

Colin

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>untitled</title>
<script type="text/javascript">

function checkit(els)
{
//get field
var field = els.something;
//strip whitespace
field.value = field.value.replace(/\s/g, '');
//empty?
if (/^$/.test(field.value))
{
alert('Please enter something.');
field.focus();
return false;
}
//get first character
var first = field.value.match(/^./);
if (first)
{
//make it a regular expression
var re = new RegExp(first[0], 'g');
//remove all instances of it, test for empty field
if (/^$/.test(field.value.replace(re, '')))
{
alert('Entries must not consist of all the same character.');
field.focus();
field.select();
//abort submit
return false;
}
//pro-life
return true;
}
}

</script>
</head>
<body>
<!-- call validator, pass elements object -->
<form onsubmit="return checkit(this.elements)">
<input type="text" name="something" value="" />
<input type="submit" />
</form>
</body>
</html>

Studying 'code banks' (imo) will slow down, not speed up your progress.
You'll need to read some good tutorials/textbooks and progress step by
step. Here's a good one:

http://www.amazon.com/gp/reader/0072191279/ref=sib_dp_pt/002-5845044-5143218#reader-link
http://www.regular-expressions.com/tutorial.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top