0

I have one string and i need to pass every character of that string for multiples conditions...

what i want

if one character of that string fulfills one of the multiple conditions don't evaluate this condition for the next character, but evaluate the remaining conditions for the remaining characters. other thing is i need to know when all conditions have been fulfilled. what is the best form or the most optimal way to do it?

what I've done

I try to pass every element for multiple condition with jquery $.each, I go through all the conditions and step to each condition all the string. this tells me when some element of the string fulfills one of the conditions, but it doesn't tell me when the whole string has fulfilled all the conditions.

// Multiple conditions
const conditions = [
      {
        isInvalid: function(str) {
          return !str.match(/[a-z]/g);
        }
      },
      {
        isInvalid: function(str) {
          return !str.match(/[A-Z]/g);
        }
      },
      {
        isInvalid: function(str) {
          return !str.match(/[0-9]/g);
        }
      },
      {
        isInvalid: function(str) {
          return !str.match(/[\!\@\#\$\%\^\&\*]/g);
        }
      },
      {
        isInvalid: function(input) {
          return str.length < 8;
        }
      },
    ];

const stringToCheck = 'mystring';

$.each( conditions , ( i, condition ) => {
    const isInvalid = condition.isInvalid( mystring );

    if ( isInvalid ) {
      return true

    } else {
      retur false
    }
});

1 Answer 1

2

You can save some value to an array each time a condition passes then you can compare the length of that array with the conditions array

// Multiple conditions
const conditions = [
    {
        isInvalid: function(str) {
            return !str.match(/[a-z]/g);
        }
    },
    {
        isInvalid: function(str) {
            return !str.match(/[A-Z]/g);
        }
    },
    {
        isInvalid: function(str) {
            return !str.match(/[0-9]/g);
        }
    },
    {
        isInvalid: function(str) {
            return !str.match(/[\!\@\#\$\%\^\&\*]/g);
        }
    },
    {
        isInvalid: function(input) {
            return str.length < 8;
        }
    },
];

const stringToCheck = 'mystring';

const results = [];

$.each( conditions , ( i, condition ) => {
    const isInvalid = condition.isInvalid( stringToCheck );

    if ( isInvalid ) {
        return true

    } else {

        results.push(true);
        return false
    }
});

if (results.length === conditions.length) {
    console.log('All conditions fulfilled');
}
Sign up to request clarification or add additional context in comments.

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.