我遵循了使用Ajax提交表单的教程,[Link]
如教程中所述,一切正常。表单提交后,我可以看到所需的验证,但在我添加另一个验证后,例如我有一个输入字段要求全名。我添加了验证以检查值是否小于3,如果是,则在$errors
数组中添加相应的消息。
这是我当前的验证,只检查字段是否为空。
<?php
require('includes/config.php');
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name1']))
$errors['name1'] = 'Name is required.';
if (strlen($_POST['name1']) < 3)
$errors['name1'] = 'Full name is required (both first and last name)';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['number1']))
$errors['number1'] = 'Mobile Number is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Thank you!';
}
// return all our data to an AJAX call
echo json_encode($data);
这一切都运行正常,但是当我添加另一个验证时,它都会失败。 没有验证工作。
看看我在做什么。
if (empty($_POST['name1']))
$errors['name1'] = 'Name is required.';
if (($_POST['name1']) < 3)
$errors = 'Full name is required (both first and last name)';
添加上述验证后,所有验证都失败。这有什么不对吗?
答案 0 :(得分:2)
我认为存在语法错误:
if (empty($_POST['name1']))
$errors['name1'] = 'Name is required.';
if (!empty($_POST['name1']) && strlen($_POST['name1']) < 3)
$errors = 'Full name is required (both first and last name)';
你只需将$ _POST ['name1']与错误的整数值匹配。 你必须计算char然后匹配整数。
对于电子邮件验证:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Not Valid email!
}
移动验证
$phone = '000-0000-0000';
if(!preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is not valid
}
答案 1 :(得分:1)
正如Vishal所说,第一个问题是缺乏strlen
。另一个问题是您是将错误消息直接分配给$errors
而不是$errors['name1']