Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on:


if (validateField(document.forms[0].name) == false) {
    isValid = false;
}

if (validateField(document.forms[0].email) == false) {
    isValid = false;
}

if (validateField(document.forms[0].phone) == false) {
    isValid = false;
}

if (validateField(document.forms[0].message) == false) {
    isValid = false;
}

if (checkPattern(document.forms[0].username, /^(?!.*admin$).*$/) == false) {
    isValid = false;
}

if (checkPattern(document.forms[0].password, /^.{8,}$/) == false) {
    isValid = false;
}

if (checkPattern(document.forms[0].zipcode, /^\d{5}$/) == false) {
    isValid = false;
}

if (checkPattern(document.forms[0].ssn, /^\d{3}-\d{2}-\d{4}$|\d{9}$/) == false) {
    isValid == false;
}

I am looking for ways to streamline or simplify the string of if statements as shown above since they are all interconnected. Switching between different conditions doesn't seem feasible in this scenario. Is there a more elegant solution available?

Answer №1

To validate form fields, one option is to create an array and use boolean functions as callbacks.

isValid = [
    testLength(document.forms[0].lname),
    testLength(document.forms[0].fname),
    testLength(document.forms[0].address),
    testLength(document.forms[0].summary),
    testPattern(document.forms[0].account, /^ACT\d{6}$/),
    testPattern(document.forms[0].department, /^DEPT\d{3}$/),
    testPattern(document.forms[0].project, /^PROJ\d{5}$/),
    testPattern(document.forms[0].ssn, /^\d{3}-\d{2}-\d{4}$|\d{9}$/)
].every(Boolean);

Another approach involves using arrays for property names with corresponding patterns for validation.

var keys = ['name', 'fname', 'address', 'summary'],
    patterns = [
        ['account', /^ACT\d{6}$/],
        ['department', /^DEPT\d{3}$/],
        ['project', /^PROJ\d{5}$/],
        ['ssn', /^\d{3}-\d{2}-\d{4}$|\d{9}$/]
    ],
    isValid = keys.every(k => testLength(document.forms[0][k]))
        && patterns.every((k, p) => testPattern(document.forms[0][k], p));

Answer №2

If you start with the assumption that isValid = true, you can achieve it in this way:

var form = document.forms[0];
var props = ["lname", "fname", "address", "summary"];
var isValid = props.every(prop => testLength(form[prop]))
           && testPattern(form.account, /^ACT\d{6}$/)
           && testPattern(form.department, /^DEPT\d{3}$/)
           && testPattern(form.project, /^PROJ\d{5}$/) 
           && testPattern(form.ssn, /^\d{3}-\d{2}-\d{4}$|\d{9}$/); 

You can also implement an array approach for the patterns, like so:

var form = document.forms[0];
var props = ["lname", "fname", "address", "summary"];
var patts = [["account", /^ACT\d{6}$/], ["department", /^DEPT\d{3}$/],
             ["project", /^PROJ\d{5}$/], ["ssn", /^\d{3}-\d{2}-\d{4}$|\d{9}$/]];
var isValid = props.every(prop => testLength(form[prop]))
           && patts.every(([prop, regex]) => testPattern(form[prop], regex));

The concept here is to initialize the variables form, props, and patts only once instead of doing it every time validation is needed, although it wouldn't be a problem if done otherwise.

Answer №3

When dealing with boolean values, you can utilize the logical operator &&.

var isValid = testLength(document.forms[0].lname) && 
              testLength(document.forms[0].fname) &&
              .....
              testPattern(document.forms[0].ssn, /^\d{3}-\d{2}-\d{4}$|\d{9}$/);

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

Contrary to expectations, the middleware EJS fails to render JPG files at

I am currently working on a NodeJS server using EJS. The goal of this server is to render an HTML page that contains a line of text and a jpg file. However, I am encountering an issue with the jpg file not being loaded by the server. Even though I have sp ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

Utilizing Mirth Connect to insert XML data into a MySQL database using JavaScript

I am completely new to working with Mirth, JavaScript, and MySQL. I have successfully set up a channel in Mirth to read a text file and convert it to XML. Everything is functioning properly so far. I also attempted to send the XML data to a MySQL databas ...

Guide on updating data within a file at a specific position using JavaScript

I am faced with a challenge involving a file containing the following data, Test.txt, <template class="get" type="amp-mustache"> <div class="divcenter"> /////Need to append data at this point///// </div> </template> ...

Store the encoded data in a variable

After looking at some examples, I attempted to create my own solution but encountered an issue with the Promise being stuck in a "pending" state. My goal is to store base 64 data into a variable named base64. Can anyone offer guidance on what's wrong ...

What is the best way to crop a page?

Running a React application, I am integrating a page from an external ASP.NET app. To achieve my goal of extracting only a section of the page rather than the entire content, I am unsure if it is feasible. Specifically, I aim to extract just the body of th ...

What is the best way to retrieve and display the heading of the current section that is being viewed using Bootstrap Vue's ScrollSpy feature?

I am currently using the Bootstrap Vue Scrollspy feature in my project with Nuxt js. The elements are correctly referenced and are successfully spying on the content. What I would like to achieve is having the ability to update a specific div with the curr ...

Incorporating JavaScript to dynamically load an HTML page into an iframe

I am attempting to have each option load a unique page within a frame <!DOCTYPE html> <html> <head> <script> function selectCountry() { var mylist=document.getElementById("country"); document.getElementById("frame").src=mylist.opti ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Execute a script when a post is loaded on a WordPress page

I am looking to have my jQuery script execute every time a post page is opened or loaded. I tried using echo in the script but it did not work. Where should I place the script to ensure it runs? single.php <script src="https://ajax.googleapis.com/aja ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Error message: "jQuery is not defined and occurs exclusively in Chrome."

I've been using the following code to asynchronously load my JavaScript in the head section: <script type='text/javascript'> // Add a script element as a child of the body function downloadJSAtOnload() { var element4= document.creat ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...

What could be causing the lack of responsiveness on this page?

I have created a webpage with over 1100 lines of code using JSF 2.0. The page is filled with PrimeFaces components and I have implemented JQuery to control the appearance and disappearance of these components. The webpage functions smoothly on Firefox 4.0 ...

When you include ng-href in a button using AngularJS, it causes a shift in the alignment of the text within the button

Recently, I've been delving into Angularjs with angular-material and encountered a slight issue with ng-href. I created a Toolbar at the top of my webpage, but the moment I include the "ng-href" attribute to a button, the text inside the Button loses ...

The difference between `$(document)` and `$("document")` is like night

Does a distinction exist between: $(document) and $("document")? ADJUSTMENT: also when using the .ready() method like $("document").ready() ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Adding local JavaScript to a Vue component is a great way to enhance its functionality

I am currently working on integrating a homepage concept (Home.vue) into my project. The design is based on a template that I purchased, which includes CSS, HTML files, and custom JavaScript. While most of the CSS has been successfully imported, I am havin ...

extract individual components from the google books api

It has been quite a while since I last dabbled in JavaScript, so I decided to embark on a project creating a "bookcase" to organize the books I have read and those I still want to read. One challenge I encountered was figuring out how to separate the eleme ...