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.

4
  • 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. jqueryvalidation.org Commented Dec 16, 2016 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. Commented Dec 16, 2016 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! Commented Dec 16, 2016 at 19:40
  • @ScottMarcus You're right, now I understood what you meant Commented Dec 16, 2016 at 19:57

3 Answers 3

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) {

}
Sign up to request clarification or add additional context in comments.

1 Comment

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!
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>

2 Comments

Your way seems to be interesting but I can't actually make it work. $('.req').toArray() would put all the <input class="req"> 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
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
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/

2 Comments

"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"
Thank you @brigo - that will teach me to stop reading before the end...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.