Eduardo Go Eduardo Go - 9 months ago 27
HTML Question

HTML/Javascript: Simple form validation on submit

I'm trying to validate my form with the easiest way possible, but somehow is not working and when I click submit it just takes me to the next page without giving the alert message:

HTML:

<form name="ff1" method="post" onsubmit="validateForm();">
<input type="text" name="email" id="fremail" placeholder="your@email.com" />
<input type="text" name="title" id="frtitle" placeholder="Title" />
<input type="text" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
<input type="submit" name="Submit" value="Continue" />
</form>


Javascript:

<script type="text/JavaScript">

function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return re.test(url);
}

function validateForm()
{
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
}

// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
}

// Validate Email
var email = $("#fremail").val();
if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
}
return false;
}
</script>


Here is also in jsfiddle http://jsfiddle.net/CrLsR/

Thanks in advance

Answer Source

You have several errors there. first you have to return value from the function in the html markup: <form name="ff1" method="post" onsubmit="return validateForm();">

second in jsfiddle your place the code inside onLoad which then the form won't recognize - and last you have to return true from the function if all validation success - I fixed some issues in the update:

http://jsfiddle.net/CrLsR/8/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) { } else {
        alert("Please enter only alphanumeric values for your advertisement title");
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
    }
  return false;
}