我正在将我的表单验证代码转换为函数,但问题是它给出错误已定义的$confirm
变量的未定义索引,并且还确认密码不起作用。
功能
function formValidation($action,$confirm){
$result = "";
$input = $_POST[$action];
$confirm = $_POST[$confirm];
// For Email Validation
$find = 'email';
$path = $action;
$pos = strpos($path,$find);
if(empty(user_input($input))){
$result = "$action is missing";
}elseif($pos !== false){
$email = filter_var($input, FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$result = "Email invalid format";
}
}elseif($confirm !== $_POST['password']){
$result = "password is not confirm";
}
return $result;
}
我可以通过任何方式调用函数一次,并检查所有字段并返回错误
触发
$email_err = $password_err = $username_err = $confirmPWD_err = "";
if(isset($_POST['submit'])){
$email_err = formValidation('prd_email','');
$password_err = formValidation('password','');
$username_err = formValidation('username','');
$confirmPWD_err = formValidation('password','confirm');
}
HTML
<form method="post">
<div class="form-group">
<input class="form-control" placeholder="username" name="username" type="text" />
<?php echo $username_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="email" name="prd_email" type="text" />
<?php echo $email_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="password" name="password" type="password" />
<?php echo $password_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="Confirm Password" name="confirm" type="password" />
<?php echo $confirmPWD_err ?>
</div>
<input type="submit" class="btn btn-success" name="submit" value="submit" />
</form>
答案 0 :(得分:1)
试试这个,它适合你吗?
function formValidation($action,$confirm = null){
$result = "";
$input = $_POST[$action];
if($confirm){$confirm = $_POST[$confirm];}
// For Email Validation
$find = 'email';
$path = $action;
$pos = strpos($path,$find);
if(empty(user_input($input))){
$result = "$action is missing";
}elseif($pos !== false){
$email = filter_var($input, FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$result = "Email invalid format";
}
}elseif(!empty($confirm) && $confirm !== $_POST['password']){
$result = "password is not confirm";
}
return $result;
}
并像这样调用函数
if (isset($_POST['submit'])) {
$email_err = formValidation('prd_email');
$password_err = formValidation('password');
$username_err = formValidation('username');
$confirmPWD_err = formValidation('password', 'confirm');
}