Results 1 to 2 of 2

Thread: JavaScript Newbie - Validation Script returning 'Undefined' alert

  1. #1
    Join Date
    Oct 2007
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question JavaScript Newbie - Validation Script returning 'Undefined' alert

    I am very new at this JavaScript thing, and have recently coded my first Form validation script.

    The script works exactly as it should when the conditions are not met. However, when all the conditions are met, it is returning an 'Undefined' alert.

    The script looks like this:

    Code:
    <script language=javascript>
    
    function Validate() {
    Message = ""
    Message = Message + Checkfirst_name()
    Message = Message + Checklast_name()
    Message = Message + Checkemail()
    Message = Message + Checkphone()
    Message = Message + Checkcompany()
    Message = Message + Checkstate()
    
    if (Message==""){ 
    return true;
    }
    
    else {
    alert(Message)
    return false;
    }
    
    }
    
    function Checkfirst_name() {
    FirstName=document.Form1.first_name.value
    
    if (FirstName == "") {
    Message = "First Name is required" + "\n"
    }
    else {
    Message = ""
    }
    return Message
    
    }
    
    function Checklast_name() {
    LastName = document.Form1.last_name.value
     
    if (LastName == "") {
    Message = "Last Name is required" + "\n"
    }
    else {
    Message = ""
    }
    return Message
    
    }
    
    function Checkemail() {
    Email = document.Form1.email.value
    AtPos = Email.indexOf("@")
    StopPos = Email.lastIndexOf(".")
    Message = ""
    
    if (Email == "") {
    Message = "Not a valid Email address" + "\n"
    return Message
    }
    
    if (AtPos == -1 || StopPos == -1) {
    Message = "Not a valid email address" + "\n"
    return Message
    }
    
    if (StopPos < AtPos) {
    Message = "Not a valid email address" + "\n"
    return Message
    }
    
    if (StopPos - AtPos == 1) {
    Message = "Not a valid email address" + "\n"
    return Message
    }
    
    }
    
    function Checkphone() {
    Phone = document.Form1.phone.value
    
    if (Phone == "") {
    Message = "Phone Number is required" + "\n"
    }
    else {
    Message = ""
    }
    return Message
    
    }
    
    function Checkcompany() {
    Company = document.Form1.company.value
    
    if (Company == "") {
    Message = "Company is required" + "\n"
    }
    else {
    Message = ""
    }
    return Message
    
    }
    
    function Checkstate() {
    State = document.Form1.state.value
    
    if (State == "") {
    Message = "State is required" + "\n"
    }
    else {
    Message = ""
    }
    return Message
    
    }
    
    
    
    </script>
    Any help would be greatly appreciated.
    Last edited by tech_support; 10-05-2007 at 07:27 AM.

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    tech_support, please leave a reason for your edits -- it can get confusing otherwise

    OK, let's see...
    Code:
    <script language=javascript>
    The language attribute is deprecated for type. This should look like:
    Code:
    <script type="text/javascript">
    Code:
    function Validate() {
    The convention in Javascript follows that of Java, in that functions and methods use camel case, starting with a lower-case letter. Capitalised names are generally reserved for constructor functions or namespacing objects.
    Code:
    Message = ""
    Again with the capitalisation; also, in Javascript, declaring a variable like this causes it to become global. Not only is this not necessary and bad practice, in this case it breaks your script because you also use a variable named 'Message' elsewhere: when you do, for example,
    Code:
    Message = Message + Checkstate()
    Message is first overwritten to an empty string (assuming there's no error) by this line:
    Code:
    Message = ""
    and then has the empty string appended to it, leaving you with... an empty string. To avoid this, declare the variable local by using the var keyword:
    Code:
    var message = "";
    Code:
    Email = document.Form1.email.value
    Again, capitalisation, scope, and it's considered deprecated to reference form elements like that. Instead, use the forms and elements collections:
    Code:
    var email = document.forms.Form1.elements.email.value;
    Also, there's a lot of redundancy here. You could, perhaps, use an associative array of element names and validators:
    Code:
    <script type="text/javascript">
      function Hash(/* Object */ data) {
        if(data)
          for(var x in data)
            if(data.hasOwnProperty(x))
              [x] = data[x];
      }
    
      Hash.prototype = {
        'keys' : function() {
          var r = [];
          for(var x in this)
            if(this.hasOwnProperty(x))
              r.push(x);
          return r;
        },
        'values' : function() {
          var r = [];
          for(var i = 0, k = this.keys(), n = k.length; i < n; ++i)
            r.push(this[k[i]]);
          return r;
        },
        'items' : function() {
          return zip(this.keys(), this.values());
        },
        'size' : function() {
          return this.keys().length;
        },
        'map' : function(/* function(key, value) */ f) {
          var r = [];
          for(var i = 0, k = this.keys(), n = k.length; i < n; ++i)
            r.push(f(k[i], this[k[i]]));
          return r;
        },
        'extend' : function(/* Hash */ newData) {
          var r = new Hash(this);
          for(var i = 0, k = newData.keys(), n = k.length; i < n; ++i)
            r[k[i]] = newData[k[i]];
          return r;
        }
      };
    
      var FormValidator = {
        Validators: {
          required: function(name) {
            return function(v, els) {
              return (v && []) || [name + " is required."];
            };
          },
    
          email: function(name) {
            var req = FormValidator.Convenience.required(name);
            return function(v, els) {
              var at, dot, r;
              if((at = v.indexOf("@")) < (dot = v.lastIndexOf("."))
                  && at * dot > 1)
                r = [];
              else
                r = ["Not a valid email address."];
              return r.concat(req(v, els));
            };
          }
        },
    
        validateAll: function() {
          var r = new Hash(), t;
    
          for(var x in FormValidator.validators)
            if(FormValidator.validators.hasOwnProperty(x))
              (t = FormValidator.validate(x)).length ? r[x] = t : false;
    
          return r;
        },
    
        validate: function(formIdentifier) {
          var fv = FormValidator.forms[formIdentifier],
            fe = document.forms[formIdentifier].elements,
            r = new Hash(),
            t;
    
          for(var i = 0, n = fe.length; i < n; ++i)
            if(t = fv[fe[i].name])
              (t = t(fe[i].value, fe)).length
                ? r[fe[i].name] = t
                : false;
    
          return r;
        },
    
        forms: {
          Form1: {
            first_name: FormValidator.Validators.required("First name"),
            last_name: FormValidator.Validators.required("Last name"),
            email: FormValidator.Validators.email("Email address"),
            phone: FormValidator.Validators.required("Telephone number"),
            company: FormValidator.Validators.required("Company"),
            state: FormValidator.Validators.required("State")
          }
        }
      };
    </script>
    <!-- ... -->
    <form id="Form1" action="somepage" onsubmit="
      var t;
      return (t = FormValidator.validate(this.id)).size()
        ? alert(t.items.join('\n')) || false
        : true;
    ">
    Untested.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •