Help combining two functions.

Discussion in 'JavaScript' started by pictureboarduk, Feb 23, 2009.

  1. #1
    Hi,

    I am trying to combine the two pieces of code below for a form validation script, but am having some difficulty.

    Check the form field is not empty:

    Check the field contains no special characters:

    At the top of the file, I am using:


    I want to both check the field is not empty, and also prevent special characters being inserted for security, but am not able to figure out how to combine the two.

    If anyone would be sop kind as to help me, I would be most appreciative.

    Thanks :)
     
    pictureboarduk, Feb 23, 2009 IP
  2. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    function validateMessage(fld) {
      var error = "";
    
      if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "The Message has not been filled in.\n"
      } else {
        var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
        
        for (var i = 0; i < fld.value.length; i++) {
          if (iChars.indexOf(fld.value.charAt(i)) != -1)
          {
            error = "Your username has special characters. \nThese are not allowed.\n Please remove them and try again.";
            break;
          }
        }    
      }
    
      if (error == "")
      {
        fld.style.background = 'White';
      }
    
      return error;
    }
    Code (markup):
     
    yoavmatchulsky, Feb 23, 2009 IP
    pictureboarduk likes this.