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

Display the menu and submenus by making a request with $.get()

My menu with submenu is generated in JSON format, but I am facing issues displaying it on an HTML page using the provided code. Can someone please assist me in identifying what mistakes I might be making? let HandleClass = function() { ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

Displaying JSON data in HTML using Angular

If you have a straightforward controller: controller: function($scope, $http){ $http.get(templateSource+'/object.customer') .then(function(result){ $scope = result.data; }); } The content of my object.customer file is a ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

Eliminating fillers dashes from a text

Imagine having a string filled with soft hyphens like the one below: T-h-i-s- -i-s- -a- -t-e-s-t-.- The goal is to eliminate these soft hyphens and get back the clean string: This is a test. Attempting this task in JavaScript, here's how far I&apo ...

Jspsych: Centering and aligning 3 p tags to the left on the page

Feeling pretty stuck at the moment. Here's what I have visually right now: I added a caption in Comic Sans and an arrow using MS Paint. Each line with color swatches is wrapped in a p tag. The goal is to center these p tags on the page (as they are ...

Mastering various techniques for creating styles with makeStyles in React JS Material-UI

As a newcomer to React JS and Material UI, I am experimenting with creating various styles of buttons. Each button should have a unique appearance based on attributes like name= submit, ok, cancel, confirm, alert. App.JS import CssButton from './con ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...