0

I'm using the following validation function to validate forms on my site. I would like to extend it so that it supports arrays.

For example at the moment I might use it on the following form:

<input type="text" name="agency_name">

But I would like to adapt it so that it can validate fields in the following format (posted arrays):

<input type="text" name="agency_name[]">
<input type="text" name="agency_name[]">

The function I am using is:

public function check($source, $items = array()) {
foreach($items as $item => $rules) {
    foreach($rules as $rule => $rule_value) {
        $value = $source[$item];
        $item = escape($item);

        if($rule === 'required' && empty($value)) {
            $this->addError("{$item} is required");
        } 
        else if (!empty($value)) {
            switch($rule) {
                case 'min':
                    if(strlen($value) < $rule_value) {
                        $this->addError("{$item} must be a minimum of {$rule_value} characters.");
                    }
                break;
                case 'max':
                    if(strlen($value) > $rule_value){
                        $this->addError("{$item} must be a maximum of {$rule_value} characters.");
                    }
                break;
                case 'matches':
                    if($value != $source[$rule_value]) {
                        $this->addError("{$rule_value} must match {$item}.");
                    }
                break;
                case 'unique':
                    $check = $this->_db->get($rule_value, array($item, '=', $value));

                    if($check->count()) {
                        $this->addError("{$item} already exists.");
                    }
                break;
            }
        }
    }
}
if(empty($this->_errors)) {
    $this->_passed = true;
}
}

Does anyone know how to modify it easily to support validation of array fields?

Thanks.

1
  • Side note: switch/case !== oop. Refactor conditional with polymorphism. Commented Mar 25, 2015 at 16:13

1 Answer 1

1

// Before your validation function and after the document has loaded

$("#NameOfTrigger").click(function() {
    var items = [];
    $("#NameOfFormOtParentContainer input[type=text]").each(function() {        
        items.add($(this).val);
    });        
});

//then pass the items array to your validation function

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.