Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its corresponding v-model.

The validation process is functioning correctly; however, it involves an excessive amount of if condition blocks to ensure empty validation. Despite attempting to streamline this process through mapping, I have been unsuccessful in doing so.

Below is the existing condition block:

    const inputValidation = () => {
  if (form1.value.radio3 === 'Pass') {
    validateInputField('field1', formInputs.value.txtArea1);
  }
  // Remaining if statements...

};

To tackle this issue, I created a temporary array containing objects as follows:

const tempFieldArray = [
  { radio: 'radio3', value: 'Pass', input: 'txtArea1', field: 'field1' },
  // Additional object entries...
];

Despite my efforts to map out a solution, I have not succeeded. Any suggestions on how to condense these lengthy if condition blocks into a more concise syntax?

Answer №1

I haven't verified it yet, but this solution seems promising

const validateInputs = () => {
  for (const field of fieldArray) {
    if (form.value[field.radio] === field.value) {
      checkInput(field.field, form.value[field.input]);
    }
  }
}

Answer №2

assuming you have access to the trigger field and update tempArray to tempObject

const tempFieldProp = 
    { 
      field1 : {radio: 'radio3', value: 'Pass', input: 'txtArea1' }, 
      field2 : {radio: 'radio4', value: 'Pass', input: 'txtArea2' }, 
      field3 : {radio: 'radio4', value: 'fail', input: 'txtArea6' }, 
      field4 : {radio: 'radio5', value: 'fail', input: 'txtArea3' }, 
      field5 : {radio: 'radio6', value: 'Pass', input: 'txtArea4' }, 
      field6 : {radio: 'radio6', value: 'fail', input: 'txtArea5' }, 
      field7 : {radio: 'radio7', value: 'fail', input: 'txtArea7' }, 
      field8 : {radio: 'radio8', value: 'fail', input: 'txtArea8' }, 
      field9 : {radio: 'radio9', value: 'fail', input: 'txtArea9' }
    }
  

    const inputValidation = (field) => {
        let props = tempFieldProp[field]
        return formInputs.value[props.radio] == props.value ? ()=> validateInputField(field, formInputs.value[props.input]) : ()=>{}
    }()

execute the function and apply it

if you cannot access the trigger field

const tempFieldArray = [
  { radio: 'radio3', value: 'Pass', input: 'txtArea1', field: 'field1' },
  { radio: 'radio4', value: 'Pass', input: 'txtArea2', field: 'field2' },
  { radio: 'radio4', value: 'fail', input: 'txtArea6', field: 'field3' },
  { radio: 'radio5', value: 'fail', input: 'txtArea3', field: 'field4' },
  { radio: 'radio6', value: 'Pass', input: 'txtArea4', field: 'field5' },
  { radio: 'radio6', value: 'fail', input: 'txtArea5', field: 'field6' },
  { radio: 'radio7', value: 'fail', input: 'txtArea7', field: 'field7' },
  { radio: 'radio8', value: 'fail', input: 'txtArea8', field: 'field8' },
  { radio: 'radio9', value: 'fail', input: 'txtArea9', field: 'field9' },
];

tempFieldArray.map((field) => 
 formInputs.value[field.radio] === field.value ? 
       validateInputField(field.field , formInputs.value[field.input]) : else-function
)

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

Navigating a jQuery collection using iteration

My goal is to loop through an array and set values to an element in the following manner: <tool>hammer</tool> var tools = ["screwdriver", "wrench", "saw"]; var i; for (i=0; i < tools.length; ++i){ $("tool").delay(300).fadeOut().delay(100). ...

Handling exceptions in the event that the backend URL resource cannot be accessed

I'm facing an issue with my Vue.js single file component where I am trying to catch exceptions when the URL requested by axios.post is unreachable. I have encapsulated the entire code in a try block, but for some reason, the alert in the catch block i ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

When using setState in the onRowSelection event with React's Material-ui tableRow, the selection cannot be properly controlled

Currently, I am working with a material-ui table https://i.stack.imgur.com/JIzLT.png and my goal is to pass selected rows to a function when the DELETE button is clicked. constructor(props) { super(props); this.state = { selecte ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

Leveraging the power of Vue.js and Vuex to extract information from a v-for loop and retrieve additional data

Currently, I am engrossed in my capstone project at our school. My tech stack includes nuxt, vue, vuex, and vuetify for the client-side rendering and express for server-side rendering. Within my code, I am aiming to retrieve data from a v-for loop and then ...

Is there a method to delay HTTP requests until the number of pending requests drops below a certain threshold (N)?

I'm in the midst of a project that involves allowing users to upload multiple files simultaneously. However, sending out numerous requests all at once can overwhelm the server and trigger a 429 (Too Many Requests) error for those requests. Is there a ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...

Customize Vuetify theme colors with your own unique color palette

Attempting to override certain classes src/plugins/vuetify.js import Vue from "vue" import Vuetify from "vuetify/lib/framework" Vue.use(Vuetify) export default new Vuetify({ theme: { primary: "#4BB7E8", ...

"Need help passing an API key in the header of a Vue.js project? I recently encountered this issue while using a

How can I include an API key in the header of a Vue.js request? I am using DRF pagination. methods: { getPostData() { axios .get("http://192.168.43.126:8000/api/?page=" + this.currentPage, { headers: { &q ...

Using alphabets or Roman numerals as an index in a Vuejs For loop: A step-by-step guide

In the Vue.js v-for loop, the default iterator starts from 0, 1, 2, 3... But how can we set the v-for to start index with i, ii, iii, or a, b, c instead of numbers? For example, consider the following content: let content = [ "Content1", &quo ...

The token endpoint in Nuxtjs auth module's configuration for auth strategies is not being triggered

Our system has two important endpoints, namely /auth and /token. The endpoint /auth is responsible for providing the authorization code required to call /token in order to obtain an access token. The utilization of NuxtJS has made the auth module a prefer ...

Why is webpack attempting to package up my testing files?

In my project, I have two main directories: "src" and "specs". The webpack configuration entrypoint is set to a file within the src directory. Additionally, the context of the webpack config is also set to the src directory. There is a postinstall hook in ...

Tips for transferring localstorage values from the view to the controller in order to utilize them as a PHP variable in a separate view

How can I pass the value from local storage as a PHP variable when using location.href in the controller after clicking a button? In the view: echo Html::button('Proceed', [ 'onclick' => " var dataVal = localStorage.g ...

javascript unable to change the text in the textarea

My application takes user input from a textarea element, calls an API to retrieve values, and then compares those values against a list of known "badwords." If a match is found, the word is highlighted in red to indicate it is spelled incorrectly. The pro ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...