The JavaScript validation function selectively bypasses certain fields and begins its validation process halfway through

Within a lengthy function (25 or more lines), this snippet provides an overview of the process. The intention is to validate each field in sequence, starting with the first one. If validation fails, an alert should pop up and focus on the problematic field.

The issue encountered is that instead of following the intended order, the validation process begins from the 'DateDue' field and moves backwards. Additionally, the alert message does not appear as expected.

This code resides in the JSHeader file and is triggered by the Submit button.

Any insights into what might be causing these discrepancies?


function validate(){
var validatemsg;
var validateflag;
validateflag = 'false';

 if(document.forms[0].LocationName.value == ''){
 validatemsg='LOCATION NAME FIELD ERROR: Location Name is required to successfully process your request.';
 validateflag='true';
 document.forms[0].LocationName.focus()
 }
 if(document.forms[0].LocPhone.value == '') {
 validatemsg='LOCATION PHONE FIELD ERROR: Location Phone is required to successfully process your request.';
 validateflag='true';
 document.forms[0].LocPhone.focus()
 }
 if(document.forms[0].LocFax.value == '') {
 validatemsg='LOCATION FAX FIELD ERROR: Location Fax is required to successfully process your     request.';
 validateflag='true';
 document.forms[0].LocFax.focus()
 }

// Around a dozen similar fields come next

 if(document.forms[0].DateDue.value == '') {
  validatemsg='DATE DUE FIELD ERROR: Date Due is required to successfully process your request.';
  validateflag='true';
  document.forms[0].DateDue.focus()
 }
  if(document.forms[0].DateDue.value.length != 10) {
  validatemsg='DATE DUE FIELD ERROR: Date Due should be in mm/dd/yyyy format.';
  validateflag='true';
  document.forms[0].DateDue.focus()
  }

  if(document.forms[0].AgreeType.value == '') {
  validatemsg='AGREEMENT TYPE FIELD ERROR: AgreementType is required to successfully process your request.';
  validateflag='true';
  document.forms[0].AgreeType.focus()
  }

 if(validateflag == 'true'){
 alert(validatemsg);
 }
 if(validateflag == 'false'){
 document.forms[0].submit()
 }
 }

Answer №1

If you want to halt the validation process at the first failure, it's essential to exit the validate() function.

To achieve this, ensure to include a return statement after each if check as shown in the modified code below:

// Define variables outside the function
var validatemsg;
var validateflag = false; /* Avoid using strings for boolean values */

function validate(){
    if (document.forms[0].LocationName.value == ''){
        validatemsg = 'LOCATION NAME FIELD ERROR: Location Name is required to successfully process your request.';
        validateflag = true;
        document.forms[0].LocationName.focus();
        return; /* <-- Crucial to exit the validator */
    }
    // Add additional if blocks below
}

if (validateflag){
    alert(validatemsg);
}
if (!validateflag){
    document.forms[0].submit()
}

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

Is it possible to manually disrupt the predetermined prototype chain of Numbers, Strings, Booleans, and Arrays in JavaScript, or reassign values to do so?

Whenever we create a new variable of the number type (let's say num1), its __proto__ is set to point to the Number Object. The __proto__ of this points to Object Core, and its __proto__ ultimately ends with null, completing the Prototype chain. My go ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

Trigger an Ajax request upon clicking the refresh button in the browser

Having trouble with Ajax Deep linking and I'm curious if it's feasible to trigger an Ajax call when the user clicks on the Browser refresh button. I attempted using beforeunload and while it does work, it still sends a request to the server afte ...

Optimizing Chrome's Precious Load Time

Encountering issues with Chrome browser auto-filling passwords, usernames, etc. Creating a problem where input field validation for emptiness is not possible in Chrome while it functions correctly in other browsers. $(document).ready(function() { ...

Placing a hyperlink following the statement document.getElementById('').innerHTML =

I have created a countdown timer and once it finishes, I want it to display "Task Completed, click here to proceed." The "Click here" should redirect to a hyperlink. However, I am unsure how to implement this functionality. Here is the Javascript cod ...

Unable to retrieve data from the specified location using axios in a Nuxt application

I am experiencing an issue where axios is not following my GET path when the project is built, although it works fine in dev mode. I am using this code to fetch local .html files and inject them into my vue component. <template> <div> ...

NextJS throwing an error: Unable to access property 'json' as it is undefined

In my NextJS environment, I have a code file in the pages folder that fetches data from an external API Rest. The code is functional as the console.log(response); line displays the JSON API response in the console. However, I encountered an error in the br ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Retrieve the value of an attribute within a controller function that is not a directive

Here is some HTML content, <button data-href="helloworld">Show href Value</button> And here is some Javascript content, $("body").on('click', 'button', function(){ console.log($(this).attr("data-href")); }); When exe ...

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

How to access elements in every document fragment

I am facing an issue with a page that contains multiple document fragments. I need to retrieve all elements from the entire page that match a specific selector, like so. document.querySelectorAll('iframe') However, this does not return elements ...

Ways to display the title of the image being viewed

I had an issue while working with the input type="file" in HTML. Every time I tried to browse a new image, the name of the image did not show up beside the button. Can anyone provide some guidance on how to fix this problem? Here is my fiddle with the cod ...

Automate populating input fields with data

I need help with a form that has four input boxes. Is it possible to automatically fill the remaining three input boxes with the value entered in the first box when the user clicks a button using JavaScript? Or should I aim to prefill the textboxes with ...

I'm having trouble retrieving the index of the map function within a function called by a button onClick() event, all of which is contained within the scope of the

Initial State const [variationData, setVariationData] = useState([ { name: "", value: [""], }, ]); Function Triggered by Button Click const addValueField = (e, index) => { e.preventDefault(); const fiel ...

Accessing an HTML DOM element and assigning it to the value of an input tag

One of the elements on my webpage has the unique identifier last_name. I am trying to extract its value and pass it to an input tag. My attempt at achieving this is shown below, but it does not work as intended. <input type="hidden" name="lastName" va ...

Guide on capturing an image of a specific div using JavaScript

Currently working on an interactive "HTML Quiz" that operates solely on JavaScript - it's pretty impressive! Upon completion, a results box will appear displaying time taken, percentage score, and number of correct answers out of 10. I envision addin ...

What is the best way to update the Label located within a Grid view using JavaScript?

How can I implement a mechanism to refresh the label inside a grid view every second in JavaScript, similar to an Ajax timer? EDIT: OnLoad="setTimeout(window.location.reload();. 1000);" what is the issue with this code or <asp:Label ID="Label2" Width= ...

`Inconsistent form variable behavior persists despite multiple ajax requests`

I'm in the process of creating a basic email submission form and I've decided to use ajax for it. The issue I'm encountering is that after successfully submitting the form once, any subsequent modifications made to the text within the form a ...

The onKeyUp event in Material-UI components does not seem to be functioning as

I am experiencing an issue with a material-ui component Grid where the onKeyUp event does not seem to be triggering as expected. Here is the code snippet: <Grid item xs={12} onKeyUp={handleClickOnKeyUp} sx={{cursor: "pointer"}} onClick= {ha ...