Running a script if form field validates as email

Go To StackoverFlow.com

0

Sorry for this most likely simple question.

I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.

The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.

$(document).ready(function() {
    $("input#SearchButton").colorbox({href: function(){
   var url = $(this).parents('form').attr('action');
   var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
    return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});

});

Then I am using this to validate the form:

function MM_validateForm() { //v4.0
  if (document.getElementById){
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
 for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
  if (val) { nm=val.name; if ((val=val.value)!="") {
    if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
      if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
    } else if (test!='R') { num = parseFloat(val);
      if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
      if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
        min=test.substring(8,p); max=test.substring(p+1);
        if (num<min || max<num) errors+='- '+nm+' must contain a number  between '+min+' and '+max+'.\n';
  } }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == ''); 

} }

Thanks!!!!

The HTML for the tigger is:

<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>

In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.

2012-04-03 21:06
by user1309010


0

You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.

Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.

$('#my_form').submit(function() {

    //validate - forget the whole thing if it fails
    if (!$('#my_field').val()) return false;

    //if we get this far, validation succeeded - do other stuff now
});

A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).

2012-04-03 21:13
by NoName
Thanks for your input. I am still confused. Where do I put the validate form code, this is the code i am using to validate the form. I edited my orignal post to include it all - user1309010 2012-04-03 22:37


0

Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.

Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.

    $('#my_form').on('submit', function(e){
    //perform validation.
    MM_validateForm('email','','RisEmail');
    //check the document variable set by the validation.
        if (!document.MM_returnValue)
        {
            //did not validate
        }else{
            //open the colorbox
            var search_btn = $('input#search');

                search_btn.colorbox({href: function(){
                   var url = $(this).parents('form').attr('action');
                   var ser = $(this).parents('form').serialize();
                    return url + '?' + ser;
            }, 
            innerWidth: "1280", 
            innerHeight: "884px", 
            iframe:true, 
            scrolling:false});

        //manually trigger the click event
        search_btn.trigger('click');
        }
    //in either instance, disable the default action to ensure the form does not follow through.
    e.preventDefault();
    });

Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.

2012-04-03 22:37
by trickyzter
I updated my code for you. I see where you are going with it, but how do i validate the email? The code i was using is above, it's auto generated by dreamweaver - user1309010 2012-04-03 22:43
I have updated the code, remove the onclick attribute from the submit button as this is no longer needed - trickyzter 2012-04-03 22:59
Thanks! It didn't work though :( The form doesn't seem to attempt to run any validation, nor does it pass anything to the colorbox, it simply runs the default form action - user1309010 2012-04-03 23:12
What version of jQuery are you running - trickyzter 2012-04-03 23:14
Version 1.7.1 of jQuer - user1309010 2012-04-03 23:19
Have you encapsulated the .submit handler within the .ready method - trickyzter 2012-04-03 23:22
function validate(form_id,email) {

var reg = /^([A-Za-z0-9-.])+\@([A-Za-z0-9-.])+.([A-Za-z]{2,4})$/; var address = document.forms[form_id].elements[email].value; if(reg.test(address) == false) {

  alert('Invalid Email Address');
  return false;

} else { $("input#SearchButton").colorbox({href: function(){ var url = $(this).parents('form').attr('action'); var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser); return url+'?'+ser; }, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false}); } - user1309010 2012-04-03 23:23

That seems to work!! :) it just doesn't like having a "+" in the email, it doesn't validate, but apart from that, appears to do the job - user1309010 2012-04-03 23:24
Of course the '+' symbol won't validate, it's not part of the regex.. - trickyzter 2012-04-03 23:32
Ads