Ensuring HTML form validation using JavaScript upon submission

I currently have a form that includes an option element and an email field at the top.

<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
    <div class="form-group">
        <h4>Please enter the following data</h4>
        <div class="form-group">
            <label for="versandart">Shipping method</label>
            <select class="form-control" id="versandart" name="versandart" autofocus>
                <option value="both">Email and Print</option>
                <option value="onlyEmail">Email Only</option>
                <option value="onlyPrint">Print Only</option>
            </select>
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" placeholder="email" name="email">
        </div>
        <button class="btn" type="submit">Send</button>
    </div>
</form>

Depending on the user's choice, I need to validate whether an email address is entered in the 'both' and 'onlyEmail' cases. Since the email field is not required in all 3 cases, I cannot solely rely on the HTML required attribute. Therefore, I attempted to validate it upon submission as follows:

 document.querySelector('form[name="send"]').addEventListener("submit", validateFields);

function validateFields(){
    var versandart = document.getElementById("versandart");
    var email = document.getElementById("email");     

    if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
        if(email.value == ''){
            email.setCustomValidity('Email must be provided');
            return false;
        }else if(CHECK HERE if Mail is not correct){
            email.setCustomValidity('Email format is not correct');
            return false;
        }else{
            //in this case email is not empty and is correct
            return true;
        }
    }
}

However, this approach is ineffective as it overrides the standard HTML validation for a valid email address. So I need to recheck the email validation at the point where it says 'CHECK HERE if Mail is not correct'.

Is this the appropriate method to handle this issue or should I consider adding an onchange listener to the versandart field and dynamically adding the required attribute to the email field based on the selected value?

Answer №1

To validate email in your else if statement, make sure to utilize the isEmail() function like shown below:

else if(email.value.isEmail()) {
    return true;
    // This will allow the form to be submitted to the PHP script.
}

The string.isEmail() method will return true if the entered pattern corresponds to an email address; otherwise, it will return false.

Ensure you also perform server-side form validation to enhance security. In case a malicious individual disables JavaScript, having only client-side validation could leave your system vulnerable – especially when not able to use the required HTML attribute for the email input.

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

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Generate a fresh array by evaluating the differences between two arrays of objects

Imagine having two arrays of objects like this: let oldBookDetails = [ {'name':'Harry pottar','amount':10, is_modified: false}, {'name':'LOTR','amount':20, is_modified: false}, {' ...

Typescript is encountering errors indicating that it is unable to locate modules for imported assets, such as images

Having trouble with TS not recognizing image imports. Although the site runs fine, TypeScript seems to have an issue identifying them: import React, { Component } from 'react'; import SlackIcon from './assets/social/slack-icon-thumb.png&apos ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

loading preloaded fonts at the optimal moment

My webfonts are loaded using Webfontloader as shown below: <script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script> <script> WebFont.load({ custom: { families: ['BlenderProBook' ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

Exploring the world of three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

There appears to be no data available from the Apollo Query

I'm facing an issue with the returned data from Apollo Query, which is showing as undefined. In my code snippet in Next.js, I have a component called Image with the src value set to launch.ships[0].image. However, when running the code, I encounter a ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

What is the best approach to modify the model value when a controller function is triggered?

This is the controller: onSelectRow : function(id){ setTimeout(function () {$scope.getSelectedRow(); }, 0); },}; $scope.getSelectedRow = function(){ var grid = $("#patientgrid"); var rowKey = grid.jqGrid('getGridPara ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

Tips for displaying JSON data within another array in a Bootstrap table

I'm working with the following JSON data that I need to display in a bootstrap table. I can easily display the single-level data, but I'm unsure how to display array within array data in the bootstrap table. [ { "seriesName": "Indian ...

Error: An unknown identifier was encountered unexpectedly when coding in Typescript for front-end development without the use of a framework

About My Current Project For my latest project, I decided to work on a basic HTML canvas without using any frameworks. To ensure type checking and because of my familiarity with it from React projects, I opted to use Typescript. Below is the simple HTML ...

Is it possible to validate multiple fields within a Vue component by integrating other components and utilizing Vee-Validate for a comprehensive validation process?

Currently, I am utilizing Vue.js version 2.5.13 along with Vee-Validate version 2.0.3. Here is the structure of my code: ./component-one.vue: <template> <div> <input type="text" name="input_one" id="input_one" v-model="in ...

What is the best way to obtain the output of the MULTIPLO.SUPERIOR function using JavaScript?

In Microsoft Excel, there is a function called upper multiple where we can input a number and it will round up to the nearest multiple of a second specified number - for example: 10,986 ; 5 = 15 105,32 ; 5 = 110 ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

``There seems to be an issue with the functionality of JSON.stringify

Upon attempting to use the JSON.stringify() method to convert an array of strings into a JSON object for passing to a PHP script, I encountered an issue where the method did not return any meaningful output. The code provided is the only one handling the ...

Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first fr ...