Adrianopolis
Adrianopolis

Reputation: 1292

How to pass a condition via Data Attribute to JS for validation

Eng has requested that I allow them to enter special validation conditions to be passed to our Generic Validator via a data attribute such as:

data-clv_special_condition="$(this).val()=='X'"

on the JS side I would need to capture that data attribute and plug it into our validation such as:

$('[data-clv_special_condition]').each(function(){
    if($(this).data('clv_special_condition')){ 
        //Do something 
    })
});

However as you can imagine something like this would not work. Can anyone offer up any solutions for passing a condition from data attribute to JS to be ran through validation? Thanks!

Upvotes: 2

Views: 596

Answers (3)

Jan
Jan

Reputation: 5815

Rather than letting them set an entire expression, why not add a series of conditional data attributes with their own logic in your controller? Like

data-clv_equals="X" data-clv_notequals="Y" data-clv_regex="Z"

and in your validator something like

var isValid = true;

if ($(this).data('clv_equals')) {
   isValid &= $(this).data('clv_equals') === $(this).val();
}

if ($(this).data('clv_notequals')) {
    isValid &= $(this).data('clv_notequals') !== $(this).val();
}

if ($(this).data('clv_regex')) {
    var regex = new RegExp($(this).data('clv_regex'));
    isValid &= regex.test($(this).val());
}

It makes more sense both from a data perspective and from a logic perspective in your code. Separates the data from the logic and prevents you from having to parse an expression (with potentially dangerous ramifications).

Upvotes: 2

moonwave99
moonwave99

Reputation: 22817

What about saving just the name of the validator in the data attribute, like:

<input data-clv_special_condition="validatorOne" /> 

And storing the validation login in the js code, see:

var validators = {
  validatorOne: function(element) { ... },
  validatorTwo: function(element) { ... },
};

$('[data-clv_special_condition]').each(function(){
  var validatorName = $(this).data('clv_special_condition');
  if(validators[validatorName](this){ 
      //Do something 
  });
});

Upvotes: 0

Steven Moseley
Steven Moseley

Reputation: 16325

I've solved this exact problem in the past using a custom validation framework I built, though I don't think it would work for your case.

In your case, I think a simple eval() would work (even if inadvisable)?

$('[data-clv_special_condition]').each(function(){
  var success = eval($(this).data('clv_special_condition'));
  if (!success) {
    console.log("doh!");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<input data-clv_special_condition="$(this).val() == 'Yes!';" value="No!" />

Upvotes: 0

Related Questions