开发者

Is there a way to disallow word in Codeigniter's built in form validation?

O have a form that the fields are prefilled by jQuery. When a user clicks in the field, the field empties itself, and they type their information. However if they don enter information in each filed the default value is submitted. I would like to use Codeigniter's built in validation to disallow users creating an account with a first name of "First Name".

See here: otis.te开发者_运维技巧am2648.com/auth/register

Thanks, Blake


You can use a callback function:

// your rules

$this->form_validation->set_rules('first_name', 'required|callback__no_first_name');

// callback

function _no_first_name($str) {
    if ($str !== 'First Name') {
        return TRUE;
    }
    else
    {
        $this->form_validation->set_message('_no_first_name', 'You should not have "First Name as the first name"');
        return FALSE;
    }
}


I would extend the Form_validation library and turn it into a more valuable form validation rule that you could reuse easily...

example - (Change relevant info for your version of CI)

class MY_Form_validation extends CI_Form_validation {

    function __construct() {
        parent::CI_Form_validation();
    }

    function disallow_string($str,$word)
    {
        return ( strpos($str,$word) === FALSE ) ? TRUE : TRUE;
    }
}

Place above code in MY_Form_Validation.php in application/libraries

and in your validation, just use the rule like this

$this->form_validation->set_rules('first_name', 'required|disallow_string[First Name]');

note that you can then use this same rule for all fields, as other uses I can envision.


Don't write the default text as value in the field! Use this construction:

<input type="text" name="uname" id="uname" placeholder="Your name" />

If the user set the focus on this field, the text disappears. But no value is submitted if the user insert nothing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜