1

I've just put together a nice form which has taken me hours, with some natty jQuery focusout validation. The focusout attribute is attached to the input fields onload. I then re-use my validation functions by triggering the focusout event onsubmit, but what I don't know is how to disable the form submitting if any of my validation functions failed. Full example here (jsfiddle)

Cutdown example:

addLoadEvent(AttachVal);

function AttachVal(){

  $('input[name="FirstName"]').focusout(NameTest);
  $('input[name="LastName"]').focusout(NameTest);
  $('form[name="Register"]').submit(SubmitRegForm);

}

function SubmitRegForm(){

  $('input[name="FirstName"]').trigger('focusout');
  $('input[name="LastName"]').trigger('focusout');
  alert ("Submitting");       

return false;
}

Validation function:

function NameTest(){

var result = true;          
var EnteredValue = $(this).val();
var alphaExp = /^[a-zA-Z ]+$/;

    if (!(EnteredValue.match(alphaExp)))
    {
        var result = "Invalid"; 
    }   

    if (result !== true)
    {
        $(this).parent().next().children('span.ErrorDescript').text(result);
    }
    else
    {           
        $(this).parent().next().children('span.ErrorDescript').text("");        
    }

}

I tried attaching a variable in the SubmitRegForm function like this:

var FNStat = $('input[name="FirstName"]').trigger('focusout');

with the intention to check them all and submit if they all return true, but that just returns a object. Is it possible to get the response text from that function?...maybe? Or is there another way to force a halt of a Submit event that's currently running from within my individiual validation functions?

As always, any advice greatly appreciated.

Dan

Dan Twining
  • 640
  • 4
  • 17
  • 30
  • why is a boolean changing to a string? should just set it false rather than "Invalid". – robx May 23 '11 at 22:54
  • Have you looked at jQuery Validate? It'd save you a lot of code. http://docs.jquery.com/Plugins/validation, http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – Adrian J. Moreno May 23 '11 at 23:12

2 Answers2

2

The correct way to catch the form submission is like this:

$('#form').submit(function(e){
    // Unfocus and validation logic here.
    e.preventDefault();
});

The e.preventDefault() will stop the form from submitting.

Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
1

Here's an updated fiddle. What I did was in the return of the SubmitRegForm() method just see how many tick images are visible and if it's zero go ahead and submit the form.

Aaron Hathaway
  • 4,280
  • 2
  • 19
  • 17