0

I have multiple methods which validates and return Boolean value a control. what can be best way to write the logic so that it validates and highlights all invalid controls, doesn't submit form to server and in future I have to make least code change if new control is added.

Aprroach 1. And , OR logic operator will not give correct result

if ( (Method1(ctrl1) && Method2(ctrl2) && Method3(ctrl3)))
{  // not   submit to server }
  else    //submit the form

Approach 2 - still change in logic will require if new control is added for validation

var valid1 = Method1(ctrl1);
var valid2 = Method1(ctrl2);
var valid3 = Method1(ctrl3);
if(va1id1 && va1id2 && va1id3)
  // not   submit to server 
  else 
    // submit to server 
1
  • 1
    Javascript is not Java, nor is it C#. I highly recommend use learn the name of the language you're writing code in Commented Apr 15, 2018 at 4:26

2 Answers 2

1

Have an array called valid which contains the result of all validations.

  var valid = [];

  valid.push(Method1(ctrl1));
  ...

  var entry = valid.reduce(function(validity,state){
      return validity && state; //if any entry in the valid array is false the result will be false
  },true);

  if(entry){
  //do something
  }
  else{
  //do something else
  }

If a new validation check has to be added you have to add one line to the code though: valid.push(Method1(ctrln));

Sign up to request clarification or add additional context in comments.

Comments

0

The object oriented answer: have one class / object per "check". They all go into a list of some sort. The final checking works by iterating that list to call the same method there.

That only requires you to add a new class / object for each new check you need.

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.