0

I have a form that uses javascript form validation and instead of listing each variable and what to validate it against per variable, I am trying to combine all of those variables into one variable and then have them validate against a singular list of elements.

I was trying initially to assign all of the input fields to a class and have them validate against the class instead of the name element but I could not get that to work so I am trying this.

Here is my code:

<!DOCTYPE html>
<html>
<head>
<script>
   function validateForm() {
      var x = document.forms["myForm"]["input1"].value;
      var y = document.forms["myForm"]["input2"].value;
      var z = x + y;
      if (z == "123CODE" || z == "125CODE") {
        return true;} 
      else if (z != "123CODE" || z != "125CODE") {
        alert("Please enter a valid code"); return false;}

      }
</script>
</head>
<body>

<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="input1">
      <input type="text" name="input2">
      <input type="submit" value="Submit">
</form>

</body>
</html>
14
  • jquery is allowed?? or pure javascript?? Commented May 13, 2015 at 13:13
  • I am open to jquery if it works the way I want it to @GuruprasadRao Commented May 13, 2015 at 13:14
  • 2
    you have a syntax error , extra '}' at end, remove that it will work as expected Commented May 13, 2015 at 13:19
  • Check this Fiddle and let me know if this is what you want?? Commented May 13, 2015 at 13:21
  • @Holodout you dont want to access element with name , instead you want class to access ? Commented May 13, 2015 at 13:25

2 Answers 2

2

This will be your javascript submit function:

DEMO

function validateForm() {
    var x = document.forms["myForm"]["input1"].value;
    var y = document.forms["myForm"]["input2"].value;
    var z = x + y;
    if (z == "123CODE" || z == "125CODE") 
    {
        return true;
    } 
    else
    {
       alert("Please enter a valid code"); 
       return false;
    }
}

Simultaneously if your code is not case sensitive you can write your if condition as -

if (z.trim().toLowerCase() == "123code" || z.trim().toLowerCase() == "125code")
Sign up to request clarification or add additional context in comments.

Comments

0
 if (z.search("123CODE")>0 || z.search("125CODE")>0)
{
}

you can write if statement like this if the search result is > 0 then condition will be true otherwise false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.