简体   繁体   English

parsley.js 远程验证响应

[英]parsley.js remote validation response

I have a question regarding parsley.js v2.0.0 and the remote validation lib.我有一个关于 parsley.js v2.0.0 和远程验证库的问题。

I'd like to custom remote validate a field and I don't know how to properly show the error message that is returned from my remote source.我想自定义远程验证字段,但我不知道如何正确显示从远程源返回的错误消息。

The response from the server is a JSON formated string that is returned as plain text like this:来自服务器的响应是一个 JSON 格式的字符串,以纯文本形式返回,如下所示:

{ "error": "my custom error message" }

This is my form input and script:这是我的表单输入和脚本:

<input type="text" id="UserLogin" maxlength="32" data-ajax-name="login" data-parsley-remote-options='{ "type": "POST",  "data": { "field": "login" } }' data-parsley-remote-validator="validateUsername" data-parsley-remote="1" data-parsley-trigger="focusout" name="data[User][login]" data-parsley-id="2315">

<script>
jQuery('#UserLogin').parsley().addAsyncValidator(
  'validateUsername', function (xhr) {
    return 200 === xhr.status;
    return 404 === xhr.status; 
  }, '/api/validationMethod'
);
</script>

In the parsley error container the default message "This value seems to be invalid" from the pattern property is shown but not the response from the server.在欧芹错误容器中,显示了来自模式属性的默认消息“此值似乎无效”,但未显示来自服务器的响应。 How can I achieve that?我怎样才能做到这一点?

Problem was solved by using the ParsleyUI methods.问题已通过使用 ParsleyUI 方法解决。

<input type="text" id="UserLogin" maxlength="32" data-ajax-name="login" data-parsley-remote-options='{ "type": "POST",  "data": { "field": "login" } }' data-parsley-errors-messages-disabled="1" data-parsley-remote-validator="validateUsername" data-parsley-remote="1" data-parsley-trigger="focusout" name="data[User][login]" data-parsley-id="2315">

<script>
jQuery('#UserLogin').parsley().addAsyncValidator(
  'validateUsername', function (xhr) {
       var UserLogin = $('#UserLogin').parsley();
       window.ParsleyUI.removeError(UserLogin,'errorUsername');
       if(xhr.status == '200')
           return 200;
       if(xhr.status == '404')
           response = $.parseJSON(xhr.responseText);
           window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
  }, '/api/validationMethod'
);
</script>

Currently, there is no standard built-in way in parsley remote to retrieve backend error message and show it frontend side.目前,在 parsley remote 中没有标准的内置方式来检索后端错误消息并将其显示在前端。 You'll have to work it yourself using maybe ParsleyUI here http://parsleyjs.org/doc/index.html#psly-ui-for-javascript to retrieve your ajax call content and attach the error to the validated field.您必须自己使用ParsleyUI在这里http://parsleyjs.org/doc/index.html#psly-ui-for-javascript来检索您的 ajax 调用内容并将错误附加到已验证的字段。

Doing some research and find more native/bulletproof solution.做一些研究并找到更多原生/防弹解决方案。

Solution 1解决方案1

Add async validator and return deferred object with error message from response.添加异步验证器并从响应中返回带有错误消息的延迟对象。

import Parsley from "parsleyjs";

Parsley.addAsyncValidator('remoteMessage', function (xhr) {
    const response = xhr.responseJSON;
    if (typeof xhr.responseJSON.error !== 'undefined') {
        return $.Deferred().reject(xhr.responseJSON.error);
    }

    return true;
}, false, {
    type: 'POST'
});

HTML: HTML:

<input name="email" type="email" data-parsley-remote="http://127.0.0.1/validate_email.php" data-parsley-remote-validator="remoteMessage" />

Disadvantage of this, you have not enough control about ajax call(eg you can't cancel them to prevent multiple requests simultaneously).这样做的缺点是,您对 ajax 调用没有足够的控制权(例如,您无法取消它们以防止同时进行多个请求)。

Solution 2解决方案2

More customizable ajax call with cancelling previous pending requests.更多可定制的 ajax 调用,取消之前的待处理请求。

import Parsley from "parsleyjs";
import axios from "axios";

const cancelTokenSources = {};
Parsley.addValidator('ajax', {
    validateString: function(value, url, parsleyInstance) {
        const name = parsleyInstance.$element.attr('name');
        const data = new FormData();
        data.append(name, value);

        const cancelTokenSource = cancelTokenSources[parsleyInstance.__id__];
        if (typeof cancelTokenSource !== 'undefined') {
            cancelTokenSource.cancel();
        }

        cancelTokenSources[parsleyInstance.__id__] = axios.CancelToken.source();
        const deferred = $.Deferred();
        axios.post(url, data, {
            cancelToken: cancelTokenSources[parsleyInstance.__id__].token
        }).then(result => {
            if (typeof result.data.error !== 'undefined') {
                deferred.reject(result.data.error);
                return;
            }

            deferred.resolve();
        }).catch(() => {});

        return deferred;
    }
});

HTML: HTML:

<input name="email" type="email" data-parsley-ajax="http://127.0.0.1/validate_email.php" />

Resources:资源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM