1

I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.

If all the inputs in the form were required I could have used something like

$('#subButton').on('click', function(e) {
    if (!$('#formName').val()) {
        e.preventDefault();
        alert("Fill all the required fields");
});

But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs. Something like:

$('#subButton').on('click', function(e) {
    if (!$('#formName.req').val()) {
        e.preventDefault();
        alert("Fill all the required fields");
    }
});

In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.

j08691
  • 204,283
  • 31
  • 260
  • 272
Brigo
  • 1,086
  • 1
  • 12
  • 36
  • 2
    There are very good jQuery form validation plugins. I would suggest using one of these. Keeps you from writing a lot of code yourself. https://jqueryvalidation.org/ – Seb Dec 16 '16 at 16:55
  • 1
    It is not a great idea to work with the `click` event of a `submit` button on a `form` as opposed to the `submit` event of the `form` that is triggered by the `click` of a `submit` button. – Scott Marcus Dec 16 '16 at 16:56
  • @Seb Sure, I check that and the other famous one, but it took me more time trying to figure out how to integrate them in my page (they have a terrible _wiki_ in my opinion) than write the whole validation on my own. I'll anyway try them again probably, for more complex validations. Thanks for the tip! – Brigo Dec 16 '16 at 19:40
  • @ScottMarcus You're right, now I understood what you meant – Brigo Dec 16 '16 at 19:57

3 Answers3

1

Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?

var hasEmptyFields = $('#formName.req').filter(function() {
    return this.value.replace(/^\s+/g, '').length; //returns true if empty
    //Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0

if (hasEmptyFields) {

}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • You're totally right about entering the `0`. I tested it but it doesn't work (sure I'm making some mistake); I didn't get what `.length > 0` should do, can you please me explain since I'm quite a newbie in Javascript/jQuery? Thanks! – Brigo Dec 16 '16 at 19:31
1

Use reduce

const submitAllowed = $('.req').toArray().reduce((result, item) => { 
   return result && (!!item.value || item.value === 0);
}, true)

if (!submitAllowed) { ... }

Here is a simple demo:

<form action="dummy.asp" onSubmit="return handleSubmit()">
    <p> You can only submit if you enter a name </p>
    <br />
    Enter name: <input class="req" type="text" name="fname">
    <input type="submit" value="Submit">
</form>

<script>
  function handleSubmit() {
    const submitAllowed = $('.req').toArray().reduce((result, item) => { 
         return result && (!!item.value || item.value === 0);
      }, true)

    return submitAllowed;
  }
</script>
Lyubomir
  • 19,615
  • 6
  • 55
  • 69
  • Your way seems to be interesting but I can't actually make it work. `$('.req').toArray()` would put **all** the `` inside an array? And I also didn't get clearly how the "empty check function" is performed on each .req with `reduce`. Sorry but I'm quite a newbie in Javascript/jQuery – Brigo Dec 16 '16 at 19:28
  • I've edited my answer. you could play around with jsfiddle a bit and things will be clearer I hope. Also read the reduce documentation that I've linked, you'll get it I promise – Lyubomir Dec 16 '16 at 19:51
0

But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs

There is an HTML5 form boolean attribute required.

required works on:

  • <input type="text" />
  • <input type="search" />
  • <input type="url" />
  • <input type="tel" />
  • <input type="email" />
  • <input type="password" />
  • <input type="date" />
  • <input type="number" />
  • <input type="checkbox" />
  • <input type="radio" />
  • <input type="file" />

Example:

input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>

Peculiarly, the StackOverflow Snippet above doesn't seem to be working.

Here's a JSFiddle to demonstrate what it should be doing:

https://jsfiddle.net/a5tvaab8/

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 1
    _"In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent"_ – Brigo Dec 16 '16 at 19:28
  • 1
    Thank you @brigo - that will teach me to stop reading before the end... – Rounin Dec 16 '16 at 19:32