...

View Full Version : Validate form field only if it is filled in.



dtrance
07-16-2004, 03:56 PM
In addition, whatever they input should be only numbers and contain at least 3 digits. Can one of you pros help me out?

Willy Duitt
07-16-2004, 06:37 PM
Try this:



<script type="text/javascript">
function validate(input){
if(input.value != '' && !input.value.match(/^\d{3,}$/)){
alert('You must enter at least three numerics\nand no alpha characters!!');
input.value = '';
input.focus();
return false;
}
}
</script>
</head>

<body>
<form onsubmit="return validate(this.test)">
<input type="text" name="test">
<input type="submit" value="Submit">
</form>


.....Willy

Edit: Or on the input....


<form>
<input type="text" name="test"
onblur="if(this.value!='' && !this.value.match(/^\d{3,}$/)){
alert('You must enter at least three numerics\nand no alpha characters!!');
this.value='';this.focus()}">
</form>

dtrance
07-16-2004, 07:13 PM
Hey Willy, thanks for the response.

I have is 3 search fields and at least one of them must be filled out before the user submits. The first part of the script accomplishes this. However, if the order number happens to be filled out, than check it to see if it has only numbers and at least 3 digits.

I figured I would take what you gave me and everything would be peachy. It seems to completely break. Here is what I have:

<script>
function ValidateForm(form1){
if ((form1.ord_no.value == "") && (form1.ord_dt.value == "") && (form1.job_no.value == "")){
alert('Input in one field is required.');
return false;}
{
if(form1.ord_no.value != '' && !form1.ord_no.value.match(/^\d{3,}$/)){
alert('The PO number must contain at least 3 digits for a partial search. Alpha characters can not be submitted.');
return false;
}

return true;
}
</script>

I also tried putting it in the input tag like this.

<input type="test" name="ord_no"onblur="if(this.value!='' && !this.value.match(/^\d{3,}$/)){
alert('You must enter at least three numerics\nand no alpha characters!!');
this.value='';this.focus()}">

It doesnt seem to effect it at all. Am I missing something?

dtrance
07-16-2004, 07:18 PM
Grrr ... perhaps I should save my changes before I post. Anyhow your second suggestion worked. Thanks Willy, I appreciate the time you took to help me out.

Willy Duitt
07-16-2004, 07:24 PM
Your welcome :thumbsup:

I only started with regular expressions a few weeks ago and each one I write brings me closer to understanding what I am doing... ;)

BTW: Your post had a typo....
<input type="test" .....
You may want to check your code....

.....Willy



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum