What is the best way to prevent a form from being submitted and conduct validation using JavaScript?

Encountered a form that is unchangeable in appearance:

<form id="mx_locator" name="mx_locator" method="post" action="search-results">

  <!-- form elements -->
  <span><input type="image" src="/images/search.png" onclick="loader()"></span>

</form>

This form is part of a CMS that automatically processes the form data and generates results when the submit button is clicked. The loader function is responsible for adding or removing a class to create an effect.

I have been assigned the task of creating a JavaScript code to validate this form. The form contains fields for zip code and city. Either one of these fields must be filled out - not both, but one or the other. Therefore, when the submit button is clicked, my JavaScript code should prevent the form from processing, check the fields, and proceed only if they meet the validation criteria.

My main concern is whether the form will still be processed regardless of the JavaScript actions, as the CMS controls its functionality. Unfortunately, I am unable to modify the HTML structure of the form, only add JavaScript code to it.

Answer №1

First step is to include the onsubmit attribute within the form tag.

<form id="mx_locator" onsubmit="return ziporcity(this)" name="mx_locator" ...

Next, incorporate a script tag in your document that either contains or links to the ziporcity function, which can be defined as follows:

<script>
function ziporcity(f) { return /\d{5}/.test(f['zipFieldName'].value) || /\S/.test(f['cityFieldName'].value); }
</script>

This straightforward validation function ensures that at least one of the conditions is true: either the zip field has 5 consecutive digits (even 9 digits would pass), and/or the city field contains non-whitespace characters.

You must update zipFieldName with the actual name specified in the name="..." attribute of the zip field in your form, and replace cityFieldName with the name of the city field.

Answer №2

<script>
$(document).ready(function() {
    $("#mx_locator").submit(function() {
      var isValid = checkIfFormIsValid();
      return isValid;  // returning false will stop the form from submitting
    });
});
</script>

Make sure to have jQuery included in your project. If you encounter a situation where the CMS is interfering with your form submission event, you can hide the original form and replace it with a new one.

<script>
$(document).ready(function() {
    // Save the original form HTML and hide it
    var myForm = $("#mx_locator");
    var formHtml = myForm.html();
    myForm.html("").hide();

    // Create a new form and insert it in place of the original form
    var myNewForm = $('<form id="mx_locator2" name="mx_locator2" .../></form>');
    myNewForm.html(formHtml);
    myNewForm.insertAfter(myForm);
});
</script>

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

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

Achieving a collapsing navbar on click in Bootstrap 5

Is there a way to collapse this navigation bar after clicking on a link, without using a JavaScript event listener or the data-bs-toggle and data-bs-target methods mentioned in this article? I tried both methods but they are not working with my code. Here ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

Utilizing Jquery to add a delay and animate the sliding up effect on a recently created element

I am looking to apply a slide-up effect to a newly created element after a specified delay. $("div[data-error='true']").delay(5000).slideUp(500, function () { $("#error-alert").remove(); }); $("div[data-success='true']").delay(5000 ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Unraveling Django's Registration and Login Process through Demonstrations

Can someone please explain in detail how to create a registration and authentication process using simple language? I have successfully implemented authentication (login) with django.contrib.auth, but now I want to set up a complete registration process in ...

Is it possible to dynamically add and remove items using React state?

I am currently working on implementing a dynamic queue of game players in my React state. The goal is to avoid hardcoding the number of players who can participate and achieve this state update using a JS FIFO queue. My objective is to create a player que ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

Locate the generated ID of the inserted child when saving the parent in MongoDB

If I have a document representing a post with comments like the one below: { "_id": "579a2a71f7b5455c28a7abcb", "title": "post 1", "link": "www.link1.com", "__v": 0, "comments": [ { "author": "Andy", "body": "Wis ...

Retrieve the unique payment ID generated from the database and present it on the frontend

Greetings, I am currently working on integrating a payment processor and I require the automated generation of the corresponding payment ID in the backend. On the frontend side, I have implemented JS to request data from the backend, but I'm facing ...

Ant Design radio group buttons are currently dysfunctional

I'm having some trouble with radio group buttons. Can anyone assist me with this issue? (your help is greatly appreciated) Current Problem: Radio Group buttons are unclickable. Not sure where the issue lies! Technologies Used: React hooks, styled-co ...

problem encountered when loading an HTML file within another HTML file using AJAX

By clicking a button, I successfully loaded a full HTML page (refer to the structure below) into another HTML page. <!--START:HTML to be loaded by ajax--> <head> <!--START: The content inside this head tag is not processed while the pag ...

Jquery animation is dragging its feet on Explorer, while other browsers are zipping along

Hey everyone, I am facing an issue with a simple jquery plugin I created for an animated menu. You can check out the entire site here: Main website My Library the "bootstrap" file The problem is that the red rectangle animates smoothly in Firefox, Op ...

Dependencies for Grunt tasks

I am facing some issues with a grunt task named taskA that was installed via npm. The task has a dependency on grunt-contrib-stylus, which is specified in the package.json file of taskA and installed successfully. However, when I run grunt default from the ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

A mistake has been identified: The object could potentially be 'null'. TS2531 for window.document

This is my first time integrating TypeScript into my project. When attempting to access something using window.document.getElementById(), I keep encountering the error: Type error: Object is possibly 'null'. TS2531 I've looked online for ...

The content inside the bootstrap modal is not visible

My goal is to trigger a modal window when a specific div is clicked using bootstrap modal. However, upon clicking the div, the screen darkens but the modal body fails to appear. Code: <html> <head> <title></title> ...

Trouble with Vue: Sibling components unable to communicate

I am encountering an issue while trying to pass data from typing.js to ending-page.js within sibling components. Despite my efforts, the emit and event hubs are not functioning as expected. However, emitting from typing.js to the parent component works sea ...

Having trouble with an AJAX request to display a template in Flask

Imagine having two radio buttons labeled 1 and 2, along with some text at the bottom of a webpage. Initially, the text value is set to -1 and no radio buttons are selected. If one of the radio buttons is clicked, the text value should change to either 1 or ...