-1

I have this code to validate and submit a contact form:

form_valid: function() {
  if (
    this.form_data.nombre &&
    this.form_data.empresa &&
    this.form_data.email &&
    this.form_data.rubro &&
    this.form_data.telefono &&
    this.form_data.consulta_por &&
    this.form_data.msg &&
    this.form_data.rcapt_response
  ) {
    return true;
  }
}

But I need to call another function when this function is on "true". I don't know if I can write:

return true;
return function2();

or if I need to write another function that checked:

if (form_valid() === true) {
  function2();
}
rhelminen
  • 678
  • 1
  • 5
  • 15
  • Example one won't work. Once you return, the code will stop executing in that block. Use your second example. – Ryan Wilson Jul 27 '22 at 21:15
  • Does [this](https://stackoverflow.com/a/72927267/3807365) help? It's how to check form on submit then cancel or go ahead with submit. – IT goldman Jul 27 '22 at 21:19

3 Answers3

0

Put the call to the other function in the return statement.

if (...) {
    return function2();
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

This code should function2 when function returns true.

if(function()){
  function2();
}
GGCover
  • 1
  • 2
  • This could solve the problem but it doesn't relate to the title of the question at least, perhaps describe why you think the question is wrong from the sample code, before giving you answer? – T. Nielsen Jul 29 '22 at 13:35
0
function form_valid() {
  const data = this.form_data
  return (
    data.empresa &&
    data.email &&
    data.rubro &&
    data.telefono &&
    data.consulta_por &&
    data.msg &&
    data.rcapt_response
  )
}

// Return the result
return form_valid() && my_other_function()
// OR if you want to store the result in a variable instead of returning it
const result = form_valid() && my_other_function()

&& will continue execution until a falsy value is encountered, so this will return false if form_valid() returns false, or call my_other_function() if it returns true. Of course there's nothing wrong with an if-statement either, this is just one possible option.

Another option could be to chain one more && at the end of the form_valid() function, like this: return (... && data.rcapt_response && my_other_function()), but I wouldn't do that unless it's logically a part of ensuring that the form is valid.

rhelminen
  • 678
  • 1
  • 5
  • 15