How to configure a Parsley custom remote using javascript, not attributes

一世执手 提交于 2019-12-13 06:54:32

问题


Similarly to this question and this question I can't figure out how to How to configure a Parsley custom remote using Javascript, when binding an individual field.

e.g. I'm trying (simplified):

$('#field').parsley({
    remote: true,
    remoteValidator: 'mycustom';
});

being the equivalent of the example:

<input name="q" type="text" data-parsley-remote data-parsley-remote-validator='mycustom' value="foo" />

after I've registered the example remote:

window.Parsley.addAsyncValidator('mycustom', function (xhr) {
    console.log(this.$element);
    return 404 === xhr.status;
}, '/api/foo');

When this executes Parsley does try to process the remote inside the internal remote function:

validateString: function validateString(value, url, options, instance) {

While the Parsley.asyncValidators does include the mycustom remote OK, the options parameter is not the options I would expect (it's the Parsely field itself which has those options as an options property). So options.validator in this context is null, and so the method picks the default, which isn't configured, and so it errors on url.indexOf. Anyway that's probably all irrelevant if I've configured it wrong.

I've looked through the documentation, samples and source code, but cannot figure out how these values are read from the config.

Update: I installed it via bower and am using dist/parsely.min.js. I cannot see the parsely.remote.js (mentioned in the docs) anywhere in the bower build so I presume it's all compiled in.


回答1:


It turns out it was the value of the remote option needs to be "remote" not true.

$('#field').parsley({
    remote: 'remote',
    remoteValidator: 'mycustom';
});

As there is no attribute value for data-parsely-remote, I'd guessed "presence of tag" would evaluate to true, not the last word of the dashed attribute.




回答2:


When you define your validateString(value, url, options, instance), the options you will receive are the options of the remote validator. This validator is defined with:

  requirementType: {
    '': 'string',
    'validator': 'string',
    'reverse': 'boolean',
    'options': 'object'
  },

So there will be a validator option ('mycustom'), possibly a reverse option, and also possible a options option.

So you could bind your field with:

$('#field').parsley({
    remote: true,
    remoteValidator: 'mycustom',
    hello: 'world',
    remoteOptions: { foo: 'bar' }
});

and access 'bar' within your validator with options.options.foo or instance.options.remoteOptions.foo, and get 'world' with instance.options.hello.



来源:https://stackoverflow.com/questions/41164450/how-to-configure-a-parsley-custom-remote-using-javascript-not-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!