I use parsley.js and I would like to integrate a validation, which checks on the server-site if the entered value is already in the database. On the server site I need more information than just the value of the input. So I need to submit more parameters (in this simplified example "obj-id" and "site-id"=.
I don't know which approach to choose. I think a custom remote validation could be the right way.
I also don't know how the response of the server has to look like.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>parsley.js Remote Validation</title>
</head>
<body>
<h1>parsley.js Remote Validation</h1>
<label for="name" class="form-label sr-only">Name</label>
<input id="name" class="form-control" name="tag[name]" required
data-obj-id="200" data-site-id="100"
data-parsley-remote
data-parsley-remote-validator='check-dupliate'
data-parsley-required-message="Please enter a name!"
>
<button type="button" class="btn btn-success btn-save">Save</button>
</body>
</html>
$('#name').parsley();
$(document).on('click', '.btn-save', function()
{
if ($('#name').parsley().validate() === true)
{
console.log('do stuff');
}
});
window.Parsley.addAsyncValidator('check-dupliate', function (xhr)
{
$element = this.$element;
console.log($element.data('obj-id'));
console.log($element.data('site-id'));
return 404 === xhr.status;
}, document.URL, );
According to the documentation, you can use the attribute data-parsley-remote-options
to pass extra settings to your validator, in order to give more context to your API endpoint, without making a custom validator.
According to your snippet, it would like something like that
<input
id="name"
class="form-control"
name="tag[name]"
required
data-parsley-remote-options='{"type": "POST", "dataType": "jsonp", "data":{"obj_id":"200","site_id":"100"}}'
data-parsley-remote
data-parsley-required-message="Please enter a name!"
/>
This object {"type": "POST", "dataType": "jsonp", "data":{"obj_id":"200","site_id":"100"}}
will make a POST
call and will send data
along with the value of your field.
Here is your updated Fiddle with POST
call and 3 values sent as form post values to the endpoint.