Jump to content

JavaScript Form Validation (First attempt)


Gingerclaire_

Recommended Posts

I was wondering if someone could help me. We were learning some basic javascript in class and I can't seem to get my form to validate. Basically all I wanted it to do is return an error when nothing is entered in the field. I've done it the way we were taught in class via examples. Any help would be much appreciated!!

index.html

Link to comment
Share on other sites

  • 2 weeks later...

Thanks guys! I've check it again and it is now validating. Just not for the name though (I can still submit it without a name).

<script type="text/javascript">function validateForm() {    if (false === validate_required(    document.forms["myForm"]["name"], "Name must be supplied")) {        return false;    }    if (false === validate_required(    document.forms["myForm"]["email"], "Valid email must be supplied")) {        return false;    }    return true;}function validate_required(field, alerttxt) {    if (field.value === null || field.value == "") {        alert(alerttxt);        return false;    } else {        return true;    }}      </script>     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script>$("document").ready(function () {    $("form").validate();});</script>
Link to comment
Share on other sites

Does anyone know how to change the css and text on the form to indicate an error instead of the pop up message? We've been told to use this file:

<script type="text/javascript" scr="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

but I've really no idea where to start!?

Link to comment
Share on other sites

It looks like there are plenty of plugins to do that:https://www.google.com/search?client=opera&q=jquery+form+validation&sourceid=opera&ie=UTF-8&oe=UTF-8If you want to do it yourself, the basic idea is to put an empty element like a span or something near each field where you can write error messages for that field.

Link to comment
Share on other sites

Consider

function validate_required(field, alerttxt) {  if (field.value === null || field.value == "") {    //alert(alerttxt);    document.getElementById('errout').textContent = alerttxt;    return false;  } else {    return true;  }} 

...where you have a div on your form with an id of 'errout'...

<div id="errout"></div>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...