user1216323
user1216323

Reputation:

Codigniter validation for exact maching of string

I want to setup my validation rules in codeigniter such as a field starts with character 'P' or 'S', other wise it is invalid. How can I do that using Codigniter validation library?

Test Case 1: input: A145874 ------- invalid Must start with P or S
Test Case 2: input: P258741 -------   valid
Test Case 3: input: P45KK91 ------- invalid Must not contain Letters in other positions rather the first one.
Test Case 4: input: S457821 -------   valid

Upvotes: 1

Views: 250

Answers (1)

Colin Brock
Colin Brock

Reputation: 21575

You would need to write a custom validation rule. Something like this:

public function check_first_char($str) {
    $first_char = substr($str, 0, 1);
    if ($first_char != 'P' || $first_char != 'S') {
        $this->form_validation->set_message('check_first_char', 'The %s field must begin with P or S!');
        return FALSE;
    } else {
        return TRUE;
    }
}

Then you would add that validation rule like this:

$this->form_validation->set_rules('field_name', 'Field Name', 'callback_check_first_char');

The documentation explains it all pretty clearly.

Upvotes: 2

Related Questions