Ilyas Mimouni Ilyas Mimouni - 5 months ago 9
jQuery Question

Detect the name of required field and not validated when submit a form

I create a form in html5 like this example :

<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>

....

<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>


<script>
$('form').submit(function(){
console.log('test');
});
</script>


The problem :



I want to detect the name of the required field that are not validated when submiting and logging it.

for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."

is there a way to do this ?

thank you.

Answer

Here you go.. Loop through each input:required field and get its name with .attr.

$('form').submit(function(e) {
  e.preventDefault();
  $(this).find('input:required').each(function(){
    console.log($(this).attr('name'));  
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
  <div class="row">
    name
    <input name="name" required/>
  </div>
  <div class="row">
    type
    <input name="type" required/>
  </div>
  <div class="row">
    year
    <input name="year" required/>
  </div>

  ....

  <div class="row">
    album
    <input name="album" required/>
  </div>
  <div class="row">
    <input type="submit" value="Save" />
  </div>
</form>


Updated

$('form').submit(function(e) {
  e.preventDefault();
  $(this).find('input:required').each(function(){
    if($(this).val()==""){ //check if its empty
      console.log($(this).attr('name'));  
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
  <div class="row">
    name
    <input name="name" required/>
  </div>
  <div class="row">
    type
    <input name="type" required/>
  </div>
  <div class="row">
    year
    <input name="year" required/>
  </div>

  ....

  <div class="row">
    album
    <input name="album" required/>
  </div>
  <div class="row">
    <input type="submit" value="Save" />
  </div>
</form>

Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..