由cakephp字段打字限制

时间:2013-12-22 08:31:30

标签: cakephp

这里我已经做了验证,如果有人在提交后输入超过6位数,他将收到消息'不超过6位!!'。但是在这里我想做另一个验证,即在发送数据之前用户将是允许在字段中输入六个以上的字符。如何解决?

这是我的模型代码

public $validate = array(
        'name' => array(
                'rule' => array('notempty'),
                'message' => 'Name is required and cannot be empty!!!',
                'required' => true,
        ),
        'ssc_roll' => array(
                'rule' => array('notempty'),
                'message' => 'S.S.C Roll is required and cannot be empty!!!',
                'rule' => array('maxLength', 6),
                'message' => 'Not more than 6 digits!!',
                'required' => true,
        ),
        'hsc_roll' => array(
                'rule' => array('notempty'),
                'message' => 'H.S.C Roll is required and cannot be empty!!!',
                'rule' => array('maxLength', 6),
                'message' => 'Not more than 6 digits!!',
                'required' => true,
        ),
        'date_of_birth' => array(
                'rule' => array('date'),
                'message' => 'Enter a valid date.',
                'required' => true,
        ),
        'mobile' => array(
                'rule' => array('notempty'),
                'message' => 'Enter a valid mobile number.',
                'required' => true,
        )

);

这里是视图代码

<div class="control-group">
                <label class="control-label" for="name">S.S.C Roll *</label>
<div class="controls">
<?php 
echo $this->Form->input('ssc_roll', array('class'=>'input-large'));
echo $this->Form->error('ssc_roll'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="name">H.S.C Roll *</label>
<div class="controls">
<?php echo $this->Form->input('hsc_roll', array('class'=>'input-large'));
echo $this->Form->error('hsc_roll'); ?>
</div>
</div>

2 个答案:

答案 0 :(得分:0)

如果要验证允许新位数的其他字段,请更改MaxLength规则以匹配允许的最大位数:

    // 4 digits instead of 6
    'zip_code' => array(
            'rule' => array('notempty'),
            'message' => 'Zip code is required and cannot be empty!!!',
            'rule' => array('maxLength', 4), 
            'message' => 'Not more than 4 digits!!',
            'required' => true,
    ),
    // 10 digits instead of 6
    'phone_number' => array(
            'rule' => array('notempty'),
            'message' => 'Phone number is required and cannot be empty!!!',
            'rule' => array('maxLength', 10),
            'message' => 'Not more than 10 digits!!', 
            'required' => true,
    ),

答案 1 :(得分:0)

您可以根据业务逻辑动态更改验证

if ( $userCanInputMoreThanSixCharacter === true ) {
     $this->validator()->getField('ssc_roll')->setRule('maxlength', array(
        'rule' => array('maxlength',10),
        'required' => true
     ));
}

或者如果条件为真,您可以删除验证

if ( $userCanInputMoreThanSixCharacter === true ) {
     $this->validator()->remove('ssc_roll');
}