简体   繁体   中英

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow). I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:

<script>
   function validation() {
     var x = document.forms["bookingForm"]["id"].value;
     if (x == "") {
       alert("Ensure all fileds are filled");
       return false;
     } else {
       sendSMS();
       alert("Success");
       return true;
     }
      }
</script>

Here is a link to an expanded part of the code for reference: https://pastebin.com/Dj5fA3gB

If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();

 <!DOCTYPE html> <html> <body> <form onsubmit="validation()" name="bookingForm"> First Name: <input type="text" name="id" value="Donald"><br> Last Name: <input type="text" name="lname" value="Duck"> <input type="submit" value="Submit" /> </form> <script> function validation() { event.preventDefault(); var x = document.forms["bookingForm"]["id"].value; if (x == "") { alert("Ensure all fileds are filled"); return false; } else { sendSMS(); alert("Success"); return true; } } </script> </body> </html>

The general syntax for accessing a form element and element's value are:

document.forms[number].elements[number]


document.forms[number].elements[number].value

As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.

Looks something like this.

 <form> <input type="text" name="example" required> <input type="submit" name="send"> </form>

The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.

You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.

<form onsubmit="return validation()" method="POST"
                    action="">

remove the "name" attribute from form tag and add action attribute. Within the parenthesis in the action attribute, mention what happen if your validation success Ex:(this code help you understand "action" attribute)

<form onsubmit="return productsvalidationform();" method="POST"
                    action="AddProductServlet">

when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet). so that mention where do you need to redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM