Codeigniter's regex match

前端 未结 2 491
無奈伤痛
無奈伤痛 2020-12-10 20:14

I have this regular expression for validation in javascript:

/^(?:\'[A-z](([\\._\\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*\')$/

Now I want the same

相关标签:
2条回答
  • 2020-12-10 20:18

    Though there is no regex_match() method in CodeIgniter validation library, It's not listed in the CI User Guide.

    Per @Limon's comment:

    There is a bug in CodeIgniter with the pipe |, it breaks the regex.

    CodeIgniter uses | as a separator between validate methods.

    Therefore, to prevent from breaking the regex, you could create a callback method in your Controller to validate the input by matching the regex:

    public function regex_check($str)
    {
        if (preg_match("/^(?:'[A-Za-z](([\._\-][A-Za-z0-9])|[A-Za-z0-9])*[a-z0-9_]*')$/", $str))
        {
            $this->form_validation->set_message('regex_check', 'The %s field is not valid!');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
    

    Then add the validation rule, as follows:

    $this->form_validation->set_rules('username', 'Nombre de usuario', 'required|min_length[2]|max_length[15]|callback_regex_check|is_unique[user.username]');
    
    0 讨论(0)
  • 2020-12-10 20:19

    You might provide rules as an array :

    $this->form_validation->set_rules('username', 'Nombre de usuario', array('required', 'min_length[2]', 'max_length[15]', 'regex_match[/^(?:\'[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*\')$/]', 'is_unique[user.username]'));
    

    This way regex with pipes won't crash

    0 讨论(0)
提交回复
热议问题