0

I have the following code which I use in various places

  if(!value[field]){
    errors[field] = `${FIELDS[field].errorMessage}`;    
  }  

Is it possible to set this as a variable in javascript?

I thought of putting this as a property of an object and calling it from there. Below is my code

   _.each(FIELDS, (type, field) => {
     if (FIELDS[field].validate) {
       if (!value[field]) {
         errors[field] = `${FIELDS[field].errorMessage}`;
       }

       switch (FIELDS[field].formType) {
         case "email":
           if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value.email)) {
             errors.email = 'Invalid email address'
           }
         default:
           if (!value[field]) {
             errors[field] = `${FIELDS[field].errorMessage}`;
           }
       }
     }
   });
   return errors;
}
6
  • Can you add complete code with demo. minimal reproducible example Commented May 5, 2016 at 4:58
  • Set what as a variable? Variables do not contain code. Do you mean define it as a function which you can call from "various places"? Commented May 5, 2016 at 5:01
  • @Tushar I added my demo code Commented May 5, 2016 at 5:03
  • @torazaburo Yes, I was thinking to do something like this var check = { func : (function(){...;})() }; but was wondering if there were other methods Commented May 5, 2016 at 5:04
  • You mean like var isNotPresent = !value[field]; and then call it like if(isNotPresent){...} ? is that what you mean? Commented May 5, 2016 at 5:06

2 Answers 2

2

One thing you could probably try is saving this as a string to a variable and running eval when you need , but it might be a bit slow and issues might come up if your program is asynchronous

var condition ="if(!value[field]){errors[field]=`${FIELDS[field].errorMessage}`;}"

and then just run eval(condition) for where ever you want it

for(var x = 0 ; eval(condition);x++){}
Sign up to request clarification or add additional context in comments.

Comments

0

Define a function setError:

function setError() {
  if(!value[field]) {
    errors[field] = `${FIELDS[field].errorMessage}`;    
  }
}

Place this inside the arrow function you are passing to _.each.

Then each place you want to use it just invoke it:

setError();

That's what functions are for.

However, as your code stands, you are executing this twice, once at the top, and another time inside the default case. Why are you doing that?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.