PHP/JQuery/AJAX表单-服务器端验证只使用内线错误样式。

时间:2022-11-23 17:42:10

I'm working on a form that submits via AJAX and is processed using PHP. I am looking to have server side validation with inline styling to correspond to whichever field(s) are are not valid. I have a setup that mostly works, however, it only every validates one field at a time.

我正在开发一个通过AJAX提交并使用PHP处理的表单。我正在寻找具有内联样式的服务器端验证,以对应于无效字段。我有一个基本可以工作的设置,但是,它每次只验证一个字段。

i.e. if the user tries to submit the form but leaves 2 fields blank, only the first of those 2 is highlighted with the .error-field class I created. I'd rather that any and all fields that have errors be highlighted at once. I know I can do such a thing in jQuery by using a loop, but I'm wondering if that's something that is possible here using only server-side validation? I don't want to print an error message for each field as the form is very small and I have very little space to work with. I'd prefer to just highlight the field(s) that produce an error then display the "Please fill in the required fields" message.

例如,如果用户试图提交表单,但留下两个字段为空,那么只有两个字段中的第一个用我创建的.error-field类突出显示。我希望所有有错误的字段都同时突出显示。我知道我可以通过使用一个循环来实现jQuery,但是我想知道,在这里是否可以只使用服务器端验证?我不想为每个字段打印错误消息,因为表单非常小,我几乎没有工作空间。我只想突出显示产生错误的字段,然后显示“请填写所需的字段”消息。

The HTML for the form:

表单的HTML:

<form method="post" enctype="multipart/form-data" class="signupForm">
    <a class="sidebar">
        <span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
    </a>
    <a class="closeBtn">
        <span class="glyphicon glyphicon-remove"></span>
    </a>

    <h2 class="text-center black">Sign up for our newsletter.</h2>

    <p class="errors-container light">Please fill in the required fields.</p>

    <div class="success">Thank you for signing up!</div>
    <div class="form-field-content">
        <div class="form-group">
            <input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
                   autofocus="">
        </div>
        <div class="form-group">
            <input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
                   autofocus="">
        </div>
        <div class="form-group">
            <input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
                   autofocus="">
        </div>

        <div class="form-group submit-button">
            <button class="btn btn-primary btn-block button-submit" type="button">SIGN-UP</button>
            <img src="/img/ajax-loader.gif" class="progress" alt="Submitting...">
        </div>
    </div>
    <br/>                    
</form>

The jQuery + AJAX:

jQuery + AJAX:

;(function ($) {
    $(document).ready(function () {
        var FirstName = $('.FirstNameTxt');
        var LastName = $('.LastNameTxt');
        var EmailAddress = $('.EmailTxt');
        var successMessage = $('.success');
        var error = $('.errors-container');
        var submitbtn = $('.button-submit');
        var SubmitProgress = $('img.progress');

        var formdata = {};
        submitbtn.click(function (e) {
            resetErrors();
            postForm();
        });

        function resetErrors() {
            $('.signupForm input').removeClass('error-field');
        }

        function postForm() {
            $.each($('.signupForm input'), function(i, v) {
                if (v.type !== 'submit') {
                    formdata[v.name] = v.value;
                }
            });

            submitbtn.hide();
            error.hide();
            SubmitProgress.show();

            $.ajax({
                type: "POST",
                data: formdata,
                url: 'submission.php',
                dataType: "json"
            }).done(function (response) {
                submitbtn.show();
                SubmitProgress.hide();
                console.log("here");
                for (var i = 0; i < response.length; i++) {
                   var status = response[i].status;
                   var field = response[i].field;
                   if (status == "error") {
                     error.show();
                     $('input[name="' + field + '"]').addClass('error-field');
                   }
                    else if (status == "success") {
                        $('signupForm')[0].reset();
                        $('.form-field-content').hide();
                        successMessage.show();
                        $('.button-submit').html("Submitted");
                    }
                }
            });
        }
    });
}(jQuery));

The php code that handles the form:

处理表单的php代码:

$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$emailfield = $_POST['email'];

$return = [];

if($firstname == ""){
    $validatonStatus = "error";
    $errorField = "first_name";
}
else if($lastname == ""){
    $validatonStatus = "error";
    $errorField = "last_name";
}
else if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $validatonStatus = "error";
    $errorField = "email";
}
else {
    $validatonStatus = "success";
    $errorField = "";
   //send email notification

}
$return[] = array(
    "status" => $validatonStatus,
    "field" => $errorField,
);

echo (json_encode($return));

1 个解决方案

#1


2  

The PHP code just returns an array with one element, not an element for each field. It needs to add a separate element to $return for each field.

PHP代码只返回一个包含一个元素的数组,而不是每个字段的一个元素。它需要为每个字段的$return添加一个单独的元素。

It also shouldn't be using elseif, that prevents it from validating other fields when one is invalid.

它也不应该使用elseif,这样可以防止它在无效时验证其他字段。

if ($firstname == "") {
    $return[] = array('status' => 'error', 'field' => 'first_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'first_name');
}

if ($lastname == "") {
    $return[] = array('status' => 'error', 'field' => 'last_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'last_name');
}

if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $return[] = array('status' => 'error', 'field' => 'email');
} else {
    $return[] = array('status' => 'success', 'field' => 'email');
}

#1


2  

The PHP code just returns an array with one element, not an element for each field. It needs to add a separate element to $return for each field.

PHP代码只返回一个包含一个元素的数组,而不是每个字段的一个元素。它需要为每个字段的$return添加一个单独的元素。

It also shouldn't be using elseif, that prevents it from validating other fields when one is invalid.

它也不应该使用elseif,这样可以防止它在无效时验证其他字段。

if ($firstname == "") {
    $return[] = array('status' => 'error', 'field' => 'first_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'first_name');
}

if ($lastname == "") {
    $return[] = array('status' => 'error', 'field' => 'last_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'last_name');
}

if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $return[] = array('status' => 'error', 'field' => 'email');
} else {
    $return[] = array('status' => 'success', 'field' => 'email');
}