3

I'm trying to build several dynamic if statements based on the definition in the argument of the function. I should be able to run them if the particular keys and vales are provided. I can read all the keys and values, but not sure how to build a code upon them. This is the object passed as a function argument:

param = {
    'fields': {    
        'email' : {
            'match' : 'email'
        },
        'countAdults': {
            'match' : 'number',
            'range' : '1, 10'
        }
    }
};

//And this bit is trying to parse the object

$.each(param.fields, function(key, value){ // reading definitions from the parameter
    if(name == "'+key+'") $('[name="'+key+'"]').mandatory(); // define the begining of if
    $.each(param.fields[key], function(subk, subv){                        
        += '.'+subk+'("'+subv+'")'; // adding more to the if statement
    });    
}); 
return (all if statement);
}

After returning all of these if statements I would also like to run an else statement for default cases. I'm trying to move these bits of code from the body of a main function, to a place where you call the function, so that I wouldn't have to customize the body of the function each time.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
mwo
  • 85
  • 1
  • 7

1 Answers1

0

I suggest that you instead have elements where you add a class for every validation you want to have. Like this:

<!doctype html>
<html>
  <head>
    <style type="text/css">
      input.invalid { border: 1px solid red; }
    </style>
    <script
      src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
    </script>

    <script>
      $(function()
      {
        $('.email').each(function()
        {
          var input = $(this);

          input.keyup(function()
          {
            validate_as_email(input);
          });
        });
      });

      function validate_as_email(input)
      {
        var value = input.val();

        if (is_email(value))
          input.removeClass('invalid');
        else
          input.addClass('invalid');
      }

      function is_email(value)
      {
        return value.match
          (/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null;
      }
    </script>
  </head>
  <body>
    Email:<br>
    <input type="text" id="email" class="email">
  </body>
</html>
Anders Lindén
  • 6,839
  • 11
  • 56
  • 109