向表单字段添加错误的功能

时间:2018-12-21 18:40:47

标签: javascript json

我有以下javascript函数,可将错误添加到表单字段。错误数据来自我的应用程序的JSON响应。

export function mapErrorsToForm($form, errorData) {
    removeFormErrors($form);

    for (const fieldName in errorData.errors) {
        const $input = $(':input[name="' + fieldName + '"]');
        $input
            .addClass('is-invalid')
            .after('<div class="invalid-feedback">' + errorData.errors[fieldName] + '</div>')
        ;
    }
}

当我有一个字段名称(例如“ registration_form [firstName]”)时,此方法有效,但是,如果该字段名称类似于“ comment”(注释),则不会应用错误消息。这是我的错误数据的示例:

{errors: {registration_form[firstName]: "This value should not be blank.",…}, status: 400,…}
    errors: {registration_form[firstName]: "This value should not be blank.",…}
        registration_form[email]: "This value should not be blank."
        registration_form[firstName]: "This value should not be blank."
        registration_form[lastName]: "This value should not be blank."
        registration_form[plainPassword][first]: "This value should not be blank.”    
    status: 400
    title: "There was a validation error"
    type: "http://localhost:8000/docs/errors#validation_error"

{errors: {[comment]: "This value should not be blank."}, status: 400,…}
    errors: {[comment]: "This value should not be blank."}
        [comment]: "This value should not be blank."
    status: 400
    title: "There was a validation error"
    type: "http://localhost:8000/docs/errors#validation_error"

0 个答案:

没有答案
相关问题