tirenweb
tirenweb

Reputation: 31709

jQuery: selecting elements according to the beginning and the end of the name attribute

I have this code:

  <script>
  $(document).ready(function(){
  $('form').validate({

    //rules: { 'input_name': { email: true} },
    rules: { 'name^=input', 'name$=jander': { email: true} },
    messages: { 'input_name': "Jar" },

    errorPlacement: function(error, element) {
     error.insertBefore(element);
    },
    debug:true

    })

  });
  </script>

 </head> 

  <body>
<div id="jar">fasdf</div>

<form id="clar">
<p id="my_paragraph">Escribe ALGO para que haga la validacion de email</p>
<input name='input_jander' type="text" ">
<input type="submit" >

</form>

As you can see, I trying to apply the validation rule to all the input fields whose name attribute starts with "input" and ends with "jander", but it doesn't works (the error message is not showed)..

Upvotes: 0

Views: 56

Answers (2)

alex
alex

Reputation: 490153

Those keys simply map to the name attribute of the form.

However, I've ran into this issue once before, and I solved it like so...

var rules = {},
    messages = {},
    inputs = $(':input[name^="input"]').filter(':input[name$="jander"]');

inputs.each(function() {
   var name = $(this).attr('name');
   rules[name] = { email: true };
   messages[name] = { email: 'Type a proper email, mate!' };
});

$('form').validate({
    'rules': rules,
    'messages': messages
});

jsFiddle of input elements being matched.

Though you should probably come up with a saner identifier for those elements.

Upvotes: 0

mcgrailm
mcgrailm

Reputation: 17640

just give the inputs you want to target a class and target them that way it'll be much easier. Why make it harder on yourself

Upvotes: 1

Related Questions