Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Validation for all field with Required attribute

Tags:

I've searched high and low for the answer to this but can't find it anywhere.

I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.

like image 512
nbren007 Avatar asked Aug 14 '14 15:08

nbren007


People also ask

How do you make a field mandatory in JavaScript?

Required attribute: If you want to make an input mandatory to be entered by the user, you can use the required attribute. This attribute can be used with any input type such as email, URL, text, file, password, checkbox, radio, etc. This can help to make any input field mandatory.

How do you know if input is required?

Use the required property to check if an element is required, e.g. if (element. required) {} . The required property returns true when the element is required, otherwise false is returned. Here is the HTML for the examples in this article.


1 Answers

In case that input[type=submit] is used, you don't need any JavaScript

<form id="theForm" method="post" acion="">   <input type="firstname" value="" required />   <input type="lastname" value="" required />   <input type="submit" name="submit" value="Submit" />   </form> 

Working jsBin

But if input[type=button] is used for submitting the form, use the snippet below

<form id="theForm" method="post" acion="">   <input type="firstname" value="" required />   <input type="lastname" value="" required />   <input type="button" name="button" value="Submit" />   </form>  window.onload = function () {   var form = document.getElementById('theForm');   form.button.onclick = function (){     for(var i=0; i < form.elements.length; i++){       if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){         alert('There are some required fields!');         return false;       }     }     form.submit();   };  }; 

Wotking jsBin

like image 81
hex494D49 Avatar answered Oct 06 '22 20:10

hex494D49