views:

36

answers:

1

Hi, I am doing some basic form validation.

I have the following javascript function

function fullField(x,span_id)
{
var result=false;
if(x.value==0)
{
    document.getElementById(span_id).innerHTML =" Required";
    result=false;
}else{
    document.getElementById(span_id).innerHTML="";//can use tick <img src='images/site_images/tick.png' />
    result=true;
}

return result;
}

I have an input which is checked onblur

<input type='text' onblur='return fullField(this,'span1')name='first_name' />
<span id='span1'></span>

The function works, writing 'Required' into the span if the person tabs off the field without filling it in. However, when i click submit the form still submits. I think i am missing some fundamental point here because i though that if any of the fields in my form return false then the form would not submit. Is the only way to get around this to check the entire form again onsubmit?

+1  A: 

You could create a variable on the page that will be set to false if validation on a field fails and then for the form onSubmit(return(myValidationVariable)) - not the most elegant design but should work well with your current setup.

jarrett
That's a good idea. Does the returned value not stop the form being submitted?
andrew
I need to know if a returned 'false' from my function on a single will prevent a field from being submitted, or if the only way to achieve this is to check the whole form on submit.
andrew
If you return false from onSubmit it will cancel the form submit. The only problem you would have then is if you have required fields that they never touch those are not really included in your validation. Your design is not quite what people usually use. The better thing to do would be to have something where you can validate all the fields in onSubmit but that doesn't fit with your code right now.
jarrett