PDA

View Full Version : field validation in javascript


croy
05-22-2003, 03:04 PM
Hi all,

I try to validate field on a form 'on the fly'. On event onblur, I call the validation method which set back the focus to the field if the validation fails.

This kind of procedure results in an infinite loop, as I leave a bad field and click in a bad field (onblur is then called infinitely).

I tried using onchange but it doesn't work (focus couldn't be set).

I'm sure there is an easy solution (may be with a hidden field) but I can't find it.

Thanks for our help.

CRo

Chester
05-22-2003, 06:38 PM
Did you try something like this?

function checknum() {
if (somehing) {
alert('Error Msg');
document.MyForm.QTY.focus();
document.MyForm.QTY.select();
return false;
}
}

<input type="text" name="QTY" onchange="return checknum()">

croy
05-23-2003, 06:04 AM
Hi Chester,

thx for your answer.

Yes I did, the problem is that the focus still stay on the the other field.

When I click outside the box (ie in the window) it's ok.

Should run with IE5.0.

Any idea?

CRo.

Chester
05-23-2003, 03:23 PM
What does your code look like?

croy
05-24-2003, 07:41 AM
Something like that.....


<script>
function validate(field)
{
check = false; //response of the validation
if(!check)
{
window.alert("Validation failed");
elt = document.getElementById(field);
elt.focus();
return false;
}
return true;
}

</script>
<form method="POST" action="--WEBBOT-SELF--">
<!--webbot bot="SaveResults"
U-File="C:\Program Files\Apache Group\Apache\htdocs\_private\form_results.txt"
S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->
<p>

<input id="tt1" type="text" name="T1" size="20" onblur=validate("tt1")>
<input id="tt2" type="text" name="T2" size="20" onblur=validate("tt2")>

</p>
</form>

Philip M
05-25-2003, 08:18 AM
This problem of validating consecutive input fields can only be resolved if the test validation excludes a blank field, so that the second OnBlur (a field yet to be filled) is not fired by focus moving from the first.

So my solution is:-

Validate the content of each input field with OnBlur but NOT to fail the test if the field is blank or left unfilled.

At a later stage (OnSubmit) check that all required fields have an entry.

So (for example) if Field 3 is left blank, the user is directed
to complete it. Field 4 will then contain either an already validated entry (so not a problem), or will itself be blank.

croy
05-25-2003, 09:21 AM
programming could be very easy. Thanks Philip. :thumbsup: