views:

74

answers:

2
var rules = "Numeric - percentage Informational";

How do I validate an input based on the above criteria?

Do I use an array, if so, how do I use it? Split the rules or use jQuery Contains?

I have similar rules like the one above to validate my inputs.
The rules above will make sure that the input is numeric and a percentage. Informational means that it can have values such as 'NA'.

So, I am thinking for each input I go down the list of allowed validations(Numeric - percentage Informational) and determine if the input is correct.

Looking for suggestions and samples.

+1  A: 

I think this would be a possible solution:

Html:

<form id="myForm">
    <input name="newsletter" class="rule-Numeric-Informational test" />
    <input name="milkman" class="test" />
    <input name="newsboy" class="test rule-Numeric-Informational" />
</form>

Javascript:

// on submit event
var ok = true;
$("input[class*='rule-']", $("#myForm")).each(function()
{
  var classs = $(this).attr("class").split(" ");
  var rules = new Array;
  for (var ind in classs)
  {
    if (classs[ind].indexOf("rule-")==0)
    {
       rules = classs[ind].substr(4).split("-");
       break;
    }
  }

  var value = $(this).val();
  for (var indr in rules)
  {
    if (rules[indr]=="Numeric")
    {
      //if not check for this rule
      ok = false;
      alert("Numeric " + value);
      break;
    }
    if (rules[indr]=="Informational")
    {
      //if not check for this rule
      ok = false;
      alert("Informational " + value);
      break;
    }
    //.. other rules
  }

});
andres descalzo
A: 

There is a very nice form validator plug in. Take a look at http://www.position-relative.net/creation/formValidator/ If using it will not suit you then take a look at the code. It is very good and has all the hooks in place to make a different validator.

Philip Schlump