2013-03-11 120 views
0

我有自己的字段验证问题。现在,表单中有5-6个字段。所以我正在检查我的控制器中的每一个,如果有错误,我希望再次加载视图并将错误数组传递给它。传递数组以查看codeigniter

我实现这个上面的功能:

<html> 
<head> 
<title>My Form</title> 
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'> 

</head> 
<body> 


<?php 
    echo $fullname; 
?> 

<? 
echo form_open('/membership/register');  
?> 


<h5>Username</h5> 
<input type="text" name="username" value="" size="50" /> 

<h5>Password</h5> 
<input type="text" name="password" value="" size="50" /> 

<h5>Password Confirm</h5> 
<input type="text" name="cpassword" value="" size="50" /> 

<h5>Email Address</h5> 
<input type="text" name="email" value="" size="50" /> 

<h5>Mobile</h5> 
<input type="text" name="mobile" value="" size="15" /> 

<h5>Home</h5> 
<input type="text" name="home" value="" size="15" /> 

<h5>Full Name</h5> 
<input type="text" name="fullname" value="" size="100" /> 
<br><br> 
<div><input type="submit" value="Submit" /></div> 

</form> 

</body> 
</html> 

和控制器的代码是:

  if (preg_match('#[0-9]#',$fullname)) 
      { 
       $errors['fullname'] = 'wrong name format!'; 
       $this->load->view('register', $errors); 
      } 

现在真正的问题我已经是,如果许多领域都是错误的。我想要传递$ errors数组来查看并访问它包含的所有值。所以我不必指定$全名或$手机来获得价值。如何才能做到这一点?以向用户显示一切缺失

回答

0

在绑定errors之前,先在控制器中执行所有检查。

例如

$errors = array(); 

if (preg_match('#[0-9]#',$fullname)) 
{ 
    $errors['fullname'] = 'wrong name format!'; 
} 

if (do_something_to_validate(mobile)) 
{ 
    $errors['mobile'] = 'invalid mobile'; 
} 

// after checking everything do this 
$this->load->view('register', $errors); 
3

所有我建议使用的第一笨的内置表单验证类

下面是我通常处理我的验证控制器:

if ($this->input->post()) 
{ 
    // process the POST data and store accordingly 
    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|xss_clean'); 
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|xss_clean'); 
    // the rest of your form fields validation can be set here 
    if ($this->form_validation->run() == FALSE) 
    { 
     // validation hasnt run or has errors, here just call your view 
     $this->load->view('same_view_file_with_the_form', $data); 
    } 
    else 
    { 
     // process the POST data upon correct validation 
    } 
} 

在我看来,文件我呼吁每一个错误像这样:

<h5>Username</h5> 
<input type="text" name="username" value="" size="50" /> 
<span class="error-red"><?php echo form_error("username"); ?></span> 
<h5>Password</h5> 
<input type="text" name="password" value="" size="50" /> 
<span class="error-red"><?php echo form_error("password"); ?></span> 
<h5>Password Confirm</h5> 
<input type="text" name="cpassword" value="" size="50" /> 
<span class="error-red"><?php echo form_error("cpassword"); ?></span>