我在論壇上查找了類似的問題,但找不到任何能幫助我的東西。在字段旁邊顯示Php表單錯誤
我有驗證類驗證表單條目。但它將它們顯示在表格的頂部。我怎麼能顯示這些字段旁邊的字段,而不是窗體的頂部?
registration.php的
if(Input::exists()){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'fullName' => array(
'required' => true,
'min' => 4,
'max' => 20
),
'username' => array(
'required' => true,
'min' => 4,
'max' => 20,
'unique' => 'user'
),
'email' => array(
'required' => true,
'unique' => 'user'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
)
));
if($validation->passed()){
// Register User
echo('Passed');
} else {
// Output Errors
foreach($validation->errors() as $error){
echo $error, '</br>';
}
}
}
?>
<div class="registration">
<h3> Register with WebA<font style="color: #c14a44;">ww</font>ards </h3>
<p> Spare us few little seconds, and you'll be glad you did. </p>
<form method="post" action="">
<input type="text" id="fullName" value="<?php echo escape(Input::get('fullName')); ?>" name="fullName" placeholder="Your Full name">
<input type="text" id="username" value="<?php echo escape(Input::get('username')); ?>" name="username" placeholder="Choose Username" autocomplete="off">
<input type="email" id="email" value="<?php echo escape(Input::get('email')); ?>" name="email" placeholder="Email address">
<input type="password" id="password" name="password" placeholder="Password">
<input type="password" id="password_again" name="password_again" placeholder="Comfirm password">
<input id="gobutton" type="submit" value="Register">
</form>
Validate.php
public function check($source, $items = array()){
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){
$value = trim($source[$item]);
$item = escape($item);
// if rule is required and value is empty add error
if($rule === 'required' && empty($value)){
$this->addError("{$item} is required");
} else if(!empty($value)) {
// DEFINE THE RULES FOR VALIDATION MIN, MAX
// USE SWITCH STATEMENT TO SWITCH BETWEEN THE RULES AND CHECK IF VALID
// Case for each of the rules defined on the form
switch($rule){
case 'min':
if(strlen($value) < $rule_value){
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value){
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]){
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()){
$this->addError("{$item} already exists.");
}
break;
}
}
}
}
if(empty($this->_errors)){
$this->_passed = true;
}
return $this;
}
if($ validation-> passed()){ //註冊用戶 echo('Passed'); }其他{ //輸出錯誤 的foreach($ validation->誤差()作爲$錯誤){ 回聲$誤差, ''; } }我應該擺脫這一點嗎? – Tauciokas
是的。如果您不想在頁面頂部輸出錯誤,請不要在頁面頂部輸出錯誤。所有的驗證都應該在那裏發生,但是你需要將輸出移動到你想要的位置。 – deceze