Modelesq
Modelesq

Reputation: 5402

Check validation with id's and assign custom errors

(I am not using Jquery Validation)

I'm trying to return custom errors if the field is incorrect or empty. For instance, if the #id_first_name field is null. Append the string, " first name" to p#error to result in :

Please fill in your first name

I've made a fiddle here to show what I mean. So in the list of required fields... How would I be able to grab / check each individual required id and assign the corrosponding error?

Thank you for your help in advance!

Upvotes: 0

Views: 43

Answers (2)

dev
dev

Reputation: 4009

You're fiddle should be as basic as possible, removing all other information, but you could try something like this,

$('form').on('submit',function(){
   $('input').each(function(){
      $this = $(this);
      if($this.val() == 'null')
      {
         $('p#error').append('Please enter your ' + $this.attr('placeholder'));
      }
   }
});

Upvotes: 1

ShaShads
ShaShads

Reputation: 572

You could do something like below

$('form input').on('blur', function() {
     var id = $(this).attr('id');
     var val = $(this).val();
     if(id == 'myInput') {
          if(!val.length) {
              $('#error').append('Please enter a value into the input');
          }
     }
});

This is a simple way of doing form validation, just tailor the example to your needs.

EDIT

If you want it to work in your example it would be better to have a div with the id of error and append p tags with the corresponding error values.

Happy coding :)

Upvotes: 0

Related Questions