How access element attribute inside Parsley Validation

1.5k views Asked by At

I need get attributes of element inside Parsley validation, I can using jQuery and selector, but I think it not the best way, have another way to do it?

See below my validation and html code:

(function () {
  'use strict';

  // Validate xml extension.
  window.ParsleyValidator.addValidator('filetype',
      function (value, requirement) {
        var ext = value.split('.').pop().toLowerCase();

        return ext === requirement;
      }, 32)
    .addMessage('en', 'filetype', 'The selected file must be an %s file.');
}());
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://cdn.bootcss.com/parsley.js/2.0.7/parsley.js"></script>

<div class="container">
  <form class="form-horizontal" role="form" data-parsley-validate>
    <div class="form-group">
      <label for="file" class="col-sm-2 control-label">File</label>
      <div class="col-sm-4">
        <input type="file"
          name="file[]"
          id="file"
          class="form-control"
          multiple="multiple"
          data-buttonText="Escolha arquivo"
          data-iconName="fa fa-folder-open"
          data-parsley-filetype="xml"
          required>
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-10 col-sm-offset-2">
        <button type="submit" class="btn btn-default">Salvar</button>
      </div>
    </div>
  </form>
</div>

2

There are 2 answers

0
Marc-André Lafortune On BEST ANSWER

The current version doesn't really give you access; everything you need should be in requirement. It could be an array with multiple values, though.

A future should allow you to access any attribute starting with data-parsley-filetype-, but there's no way to know from your example what you are actually trying to achieve, so I don't know if that would help.

0
ShaneMit On

you need to access the argument directly:

window.Parsley
    .addValidator('customvalidator', {
        validateNumber: function (value, requirement) {
            var element = arguments[2].$element.parent();

           //logic here...

        },
        requirementType: 'integer'
    });