Troubleshooting JavaScript Form Validation Failure upon Submission

Currently, I am studying the section of a book that covers form validation using JavaScript. Unfortunately, the example in the book is not functioning as expected. Despite comprehending and following the logic behind the validation process, nothing occurs onSubmit. I have meticulously reviewed both the script and HTML multiple times but have been unable to identify any errors (I even visited the book's website and copied the code from there).

Below is the HTML form along with the JavaScript validation:


    <script>
    function validate(form) 
    {
            fail  = validateForename(form.forename.value)
            fail += validateSurname(form.surname.value)
            fail += validateUsername(form.username.value)
            fail += validatePassword(form.password.value)
            fail += validateAge(form.age.value)
            fail += validateEmail(form.email.value)
            if (fail == "") return true
            else {alert(fail); return false }
    }
    </script>

    <script>
    function validateForename(field) {
            if (field == "") return "No Forename was entered.\n"
            return ""
    }

    function validateSurname(field) {
            if (field == "") return "No Surname was entered.\n"
            return ""
    }

    function validateUsername(field) {
            if (field == "") return "No Username was entered.\n"
            else if (field.length < 5) return "Usernames must be at least 5 characters.\n"
            else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
            return ""
    }

    function validatePassword(field) {
            if (field == "") return "No Password was entered.\n"
            else if (field.length < 6) return "Passwords must be at least 6 characters.\n"
            else if (! /[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n"
            return ""
    }

    function validateAge(field) {
            if (isNAN(field)) return "No Age was entered.\n"
            else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n"
            return ""
    }

    function validateEmail(field) {
            if (field == "") return "No Email was entered.\n"
                    else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address is invalid.\n"
            return ""
    }
    </script>

</head>

<body>

    <table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
    <th colspan="2" align="center">Signup Form</th>
    <form method="post" action="adduser.php" onSubmit="return validate(this)">
    <tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" /></td>
    </tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td>
    </tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td>
    </tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" /></td>
   </tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td>
    </tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td>
    </tr><tr><td colspan="2" align="center">
    <input type="submit" value="Signup" /></td>
    </tr></form></table>
</body>
</html>

Answer №1

there doesn't seem to be any action happening upon submission

If by "nothing" you mean absolutely no activity, including the form being submitted, then the issue may lie in ensuring the HTML is valid.

It's worth noting that a form cannot enclose table rows while also being placed within the same table. Some browsers may attempt to correct this by relocating the form after the table, leaving the inputs outside of the form and essentially inactive.

A quick solution would involve repositioning the form to encompass the entire table.

For a more comprehensive remedy, consider moving away from tables for layout purposes and instead utilize CSS for effective form layouts.

Additionally, make sure to leverage the benefits of the label element, and aim to minimize the use of global variables in your JavaScript code.

Answer №2

Can you figure out how to spell "isNAN"?

To debug this code, try adding alert statements after each line of code. By using simple debugging techniques like this, you will quickly identify any issues with invalid syntax. It's up to you to locate and fix the bug!

Answer №3

To make it functional, simply substitute isNAN with isNaN.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for effortlessly inserting multiple images into a web form that are sourced from a database?

Greetings, I am currently in the process of creating a page where users can view specific car details and related photos. At the moment, I am utilizing a SQL table to store the image paths and then manually assigning each path as an "ImageUrl" attribute to ...

Struggling to connect to an express route?

I'm currently working on a MERN project and I'm encountering a small issue. When trying to make a POST request to a specific route, Express throws a 404 error and tells me that it can't find the desired route. However, everything works perfe ...

Verify whether the input value matches a list of words of unknown length retrieved from a data attribute

I am struggling with a simple word validation process that doesn't seem to be working as intended. Here's what I have so far: HTML: <div class="customfixer"> <li data-folder="something">something</li> <li data-folder= ...

Deleting a row from the table with a single click on the X icon

Is there a way to delete individual rows in a table by clicking on a close icon instead of removing all rows at once? Additionally, I am looking for a better method to display rows in a table. You can view my current implementation here: link -> jsfiddl ...

What is the best way to simulate an unexported function in Javascript jest environments?

Testing a module in my vuejs project is what I'm currently focusing on. import { getBaseUrl } from "@/application/api/baseUrl"; export default ( uri: string, requestBody: Record<string, string | number> ): void => { let form ...

Having trouble accessing `event.target.value` when selecting an item from the autocomplete feature in Material-UI with the

*** UPDATED CODE BASED ON RECOMMENDATIONS *** I am currently in the process of familiarizing myself with material-ui. I have been exploring how to incorporate event handling with material-ui components, specifically by combining an autocomplete feature wit ...

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

Resolving the issue of unintentional repetition of form submissions

After implementing the jquery/ajax code below: $('form').bind('submit', function () { $.ajax({ type: 'post', url: "Write-to.php", data: $("form").serialize(), success: function () { ...

Dynamic Translation Service for Ionic 2 and Angular 2 with ngx-translate

Currently working on an Ionic 2 app and looking to implement object translation directly from the server response instead of using a JSON file. Utilizing ngx-translate Here's an example of the object received: { "name": ["Hello", "Hola", "Bon Jour" ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

Clearing the Redux state in my app upon exiting the page

I've come across similar inquiries, but none of them quite match my situation. When a user clicks on one of the buttons in my app, it triggers a get request to fetch data and then displays that data on the screen. However, the issue arises when I nav ...

Customizing functions in JavaScript with constructor property

What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; ...

Create a JavaScript function that adds cells to a table, each containing an input field and a corresponding

I successfully developed a function that appends a table with rows and cells, then fills those cells with data from an array. However, I am now faced with the challenge of modifying it so that the generated cells contain an input field where the value= att ...

Transforming JSON object to an array of arrays using JavaScript

Attempting to extract specific values from a JSON object and store them in an array can be quite tricky. Below is an example of what this process might look like: Example: var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]}, "2 ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

How can you determine when a download using NodeJS HTTPS.get is complete?

Currently, I am facing an issue while downloading a file. My goal is to perform an action immediately after the download is complete. Specifically, I aim to import a .js file as soon as it finishes downloading. var request = https.get('https://m ...

Switched from btao to Buffer, however encountering a TypeError while trying to push to Vercel

I am currently working on an application in Next.js where I need to encode my image to base64. Initially, I used btao and it worked well until I tried deploying to Vercel, which resulted in an error stating that btao was undefined. After researching a solu ...

Breaking down an array in JavaScript using a variable as the index position

As far as I know, JavaScript arrays can be deconstructed based on a specific index by using the following method. const { 3: selectedByIndex } = arr; This code snippet assigns the value of the element at index 3 to the variable selectedByIndex. But is th ...