Ensuring the accuracy of two fields using a single submit button

Forgive me if this is overly simplistic, but as someone new to Javascript and not particularly skilled at coding, I'm struggling with validating two basic forms using a single submit button. If anyone could offer some guidance on how to tackle this, I would greatly appreciate it! Below is what I have so far:

function validateName() {
    var name = document.forms["Name"]["fname"].value;
    if (name == null || name == "") {
        alert("Please enter your first name");
        return false;
    }
}

function validateEmail() {
    var email = document.forms["Mail"]["email"].value;
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
        alert("Please enter a valid email address");
        return false;
    }
}

<style type="text/css">
</style>
<link rel="stylesheet" href="teststyle.css" type="text/css">
</head>
<body>
<form name="Name" action="MyForm.html" onsubmit="return validateName()" method="post">
First Name: <input name="fname" type="text"> <br>
<br>
Email: <input name="Mail" type="text">
</form>
<br>
<input value="Submit" type="submit"><br>
<br>
</body>

Answer №1

It's not very practical to validate two forms simultaneously since only one can be submitted at a time. The confusion seems to lie in understanding the distinction between a form and a field. Any data you want to submit together should be separate fields within a single form. For instance, in a comment section, fields like "Name", "Email", and "Comment" would each be represented by <input> elements inside a <form>. Your code structure should resemble this:

function checkName() {
    var x = document.forms["Newsletter"]["fname"].value;
    if (x == null || x == "") {
        alert("Please fill out your first name");
        return false;
    }
}

function checkEmail() {
    var x = document.forms["Newsletter"]["email"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Invalid email address");
        return false;
    }
}

You could also consolidate them into a single function

<body>
  <form name="Newsletter" action="MyForm.html" onsubmit="return checkName() && checkEmail()" >
    First name: <input name="fname" type="text"> <br>
    Email: <input name="email" type="text">
    <br>
    <input value="Submit" type="submit"><br>
  </form>
</body>

As an alternative, you could create a combined validation function

<form name="Newsletter" action="MyForm.html" onsubmit="return formIsValid()" method="post"	>

where formIsValid might look like this

function formIsValid()
{
  return checkName() &&
         checkEmail();
}

or in more detailed format

function formIsValid()
{
  if (!checkName())
    return false; // invalid name

  if (!checkEmail())
    return false; // invalid email

  // All validations passed
  return true;
}

Lastly, don't forget to place your submit button inside the form, before the closing </form> tag.

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

Can momentjs and moment-timezone function without being connected to the internet?

In my webapp, I want it to function properly in a local network even without internet access. The time is set according to the server timezone using moment-timezone. It works well when connected to the internet, but I'm curious about how it gets the t ...

Three.js: Comparing the Process of Updating Geometries with Replacing Them

In my current project, I have a complex scene filled with objects created using the ExtrudeGeometry method. These objects need to be updated every frame, with the extrusion shape and amount constantly changing. The shapes are generated using d3's voro ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

What is the best method to retrieve the value of a button that has been selected from a collection of buttons?

Within a functional component, there is an issue where the choose function keeps printing 'undefined'. I have utilized const [chosen, setchosen] = useState([]) within this code snippet. The full code has been correctly imported and the purpose of ...

Updating state in React is limited to using the `setState(...)` method

Encountering issue with setState function, here is the problem: Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the L ...

What is the best way to allow a container div to only show horizontal overflow, without relying on "display:inline-block" for its inner divs?

My coding challenge involves dynamically creating nested <div> elements within another <div> when a button is clicked. Upon clicking the button, a new inner <div> with a unique id is generated inside the outer <div>, each possessing ...

Display varying information depending on the option class, rather than its value

On my website, I have multiple forms structured like this: <form action="" method="post"> <input type="text"> <select name="a"> <option class="hide-all">Choose</option> <option class="show-link">Show link</option ...

Executing various actions on a single route by utilizing request type in Zend Framework 2

Looking to implement ZF2 RESTful responses for various request types. In my module.config.php, the router configuration looks like this: 'router' => array( 'routes' => array( 'student' => array( ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

Showing an element using the PHP echo command by triggering a mouseover event on another element within the same echo statement

I am currently outputting data from a MySQL table using PHP and the "echo" command to display the results. I would like a certain element within the echo to be visible when I hover over another element within that same echo. The issue is that when I use ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...

An error occurred while trying to access the object null in React-Native, specifically when evaluating 'this.state.token'

I encountered an error while trying to execute a class in a view: When running the class, I received the following error message: null is not an object (evaluating 'this.state.token') The problematic class that I'm attempting to render: c ...

The message sent by the node containing a large body (1.3 mb) encountered an error: 413 Request Entity Too Large

Using Fiddler, I am creating a POST message with a header. Content-Type: application/text-enriched app.post('/books',function(req,res){ var writeStream = fs.createWriteStream('C://Books.txt' ,{ flags : 'w' }); ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

Tips for updating an object variable dynamically in an Angular application

const person = { "name": "jacob", "age": 22 } I am looking to dynamically update it to: { "name": "jacob", "age": 22, "dob": number } ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Clean up HTML with jQuery or JavaScript

I have a small HTML-WYSIWYG editor on my CMS and I'm curious if there is a reliable script available for cleaning up HTML on the client-side. I often encounter issues with HTML copied from Microsoft Word. Maybe using some regex could solve this proble ...

What is the best way to emphasize colors in search results?

Is it possible to assist in highlighting the searched words in yellow? Below is an example of code that filters words from the displayed data from a JSON feed URL. angular.module('sample', []). controller('sampleController', [' ...

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...