Javascript Validation for all field with Required attribute - javascript

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.

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

Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)

You can use Constraint validation API, which is supported by most browsers.

I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.

this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});

If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.

Related

JavaScript input type validation

I can't seem to figure out the proper JavaScript to validate this form. Please help/provide feedback!
Essentially, my script should validate whether the user has entered data in the input text box, has checked a radio button, has checked at least one checkbox, and has selected an option from the select items.
Also the form uses a submit button to invoke the validation script, so that the form is processed only when the form fields are validated and accepted. If a field is invalid then display a message to the user.
Also need to make sure the form doesn't automatically reset every time the user gets a validation error.
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
Your validate function could look like this...
function validate() {
var form = document.forms.VacayForm;
var name = form.name;
var domInt = form.domint;
var continent = form.continent;
var agree = form.agree;
if (!name.value) {
alert( "Please provide your name!" );
name.focus();
return false;
}
if (!domInt.value) {
alert( "Please select domestic or international preference to proceed" );
domInt.focus();
return false;
}
if (!continent.value) {
alert("Please select where you prefer to visit");
continent.focus();
return false;
}
if (!agree.checked) {
alert("Please check agree to continue");
agree.focus();
return false;
}
return true;
}
This article from Javascript.info website teaches how to use forms and form elements...

How can I apply CSS to a link if at least one input is not original, and undo that change if all inputs are original?

I have a bunch of checkboxes, radio buttons, and text fields on my page. They all have '_boom' appended to the end of the id. I want to detect if any one of these inputs is not its original value, and if so, apply CSS to a button called 'save' on the page. Then, if the user reverts any changes they made and all inputs have their original values, I want to undo the CSS.
I've gotten close with the code below. But let's say I check 3 checkboxes. Upon checking the 1st box, the CSS changes. Good! I check the 2nd and 3rd boxes. The CSS stays the same. Good! But then I uncheck ONE of the boxes, and the CSS reverts. Bad! The CSS should only revert if I undo every change.
$('[id*="_boom"]').change(function() {
var sType = $(this).prop('type'); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");
if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();
if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
});
#save {
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
There are many possible improvements in your code to make it cleaner and standardized. Things like instead of relying on id you should consider class attribute and all... but I will not revamp your code. Here's the solution to your existing code.
The idea is loop through all the form elements and if atleast one of the elements is different than its default value then set the flag and come out of the loop.
At the end, check for that flag and set the css accordingly.
For this, I have enclosed your elements into a form form1.
$("#form1 :input").change(function() {
var changed = false;
formElems = $("#form1 :input");
for(i=0;i<formElems.length; i++){
var sType = $(formElems[i]).prop("type");
if(sType === "checkbox" || sType === "radio"){
if($(formElems[i]).prop("defaultChecked") !== $(formElems[i]).prop("checked")){
changed = true;
break;
}
}else if(sType === "text"){
if($(formElems[i]).prop("defaultValue") !== $(formElems[i]).val()){
changed = true;
break;
}
}
}
if(changed){
$("a#save").css("color","#CCCCCC");
}else{
$("a#save").css("color","black");
}
});
And here is your form
<form id="form1">
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
</form>
The problem is, when one of them change to its original value, it doesn't mean there is no change.
So, in your else code block, you should check all the inputs, if all of them are the original values, remove the 'save' class from the button, otherwise, keep it.
var isChanged = function ($element) {
var sType = $element.prop('type');
if (sType === "checkbox" || sType === "radio") {
var originalCheckedState = $element.prop("defaultChecked");
var currentCheckedState = $element.prop("checked");
if (currentCheckedState !== originalCheckedState) {
return true;
} else {
return false;
}
} else if( sType === "text" ) {
var originalValue = $element.prop("defaultValue");
var currentValue = $element.val();
if (currentValue !== originalValue) {
return true;
} else {
return false;
}
}
};
var $inputs = $('[id*="_boom"]');
var isAnyChanged = function () {
$inputs.each(function () {
if (isChanged($(this))) {
return true;
}
});
return false;
};
$inputs.change(function () {
if (isChanged($(this))) {
$("a#save").css("color","#CCCCCC");
} else if (!isAnyChanged()) {
$("a#save").css("color","black");
}
});

Radio Button not Working in ie

I have 4 radio button in my form, once i submit the form any of the radio button should checked, if not a alert message will be displayed. its working properly in chrome, firefox, but in ie one i checked the radion it always showing the alert so i cant submit the form, i have given my code below please help me
PHP:
<form action="user_register.php" method="POST" name="myForm" onsubmit="return validateForm()" enctype="multipart/form-data">
<label>USERNAME:</label></td>
<input type="text" name="username" class="regtext" required/>
<label>RESIDING CITY:</label></td>
<input type="text" name="city" class="regtext" required/>
<label>I'M A</label>
<label>ARTIST &nbsp <input type="radio" value="1" name="user_type" > </label>&nbsp
<label>MODEL &nbsp <input type="radio" value="2" name="user_type"></label>&nbsp
<label>COMPOSER &nbsp <input type="radio" value="3" name="user_type" ></label>&nbsp<br>
<label>BEAT MAKER &nbsp <input type="radio" value="4" name="user_type" ></label>&nbsp
<label>NONE &nbsp <input type="radio" value="0" name="user_type" ></label>
<label> <input type="checkbox" value="1" name="letter" > &nbsp I WOULD LIKE TO RECEIVE YOUR NEWSLETTER</label>
</div>
<div class="mainhead">
<input type="submit" name="register" class="submit" value="SEND AND REGISTER NOW">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
Problem is that for IE, document.forms["myForm"]["user_type"] is an HTMLCollection and has no value
Solution is to change
var user_type = document.forms["myForm"]["user_type"].value;
to
var user_type = document.querySelector('form[name="myForm"] input[name="user_type"]:checked').value;
What i observed is :
No name province present in code (what you gave). If you include it here, it will not work.
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
After removing province validation. It started working.
<script type="text/javascript">
function validateForm() {
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
So, as Mr Rayon Dabre said "There is no element having name as province". So, i also agree with him. Remove province validation from validateForm() function (as it is not used in <from></form>)
This code should do the trick:
function validateForm() {
var user_type = document.getElementsByName('user_type');
var u_type = '';
for (var i = 0, length = user_type.length; i < length; i++) {
if (user_type[i].checked) {
// do whatever you want with the checked radio
u_type = user_type[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
if (u_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.getElementsByName('letter')[0].checked;
if (letter == "" || letter == undefined) {
alert("Select that you want to receive news letter");
return false;
}
}

How do I disable form dropdown option using javascript

I'm trying to disable the "name" text field in the form when "Choose" is selected in the drop down after the page loads (it's disabled when the page loads) ie after I've chosen one of the other two options that disable or enable that field, when I return to "Choose" i'd like the same field to disable. I can't see why the javascript I've written would prevent this from happening. Thanks!
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value === defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value === "") {
thisfield.value = defaulttext;
}
}
function checkPickup() {
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
/* Reset form values */
form.name.value = "His/her name";
}
}
</script>
<script type="text/javascript">
function validate(form) {
var errmsg = "Oops, you're required to complete the following fields! \n";
// Various other form validations here
// Validate "Pickup"
if (form.os0.value === "") {
errmsg = errmsg + " - Choose pickup or delivery\n";
}
// Validate "phone"
if (form.phone.value === "" || form.phone.value === "Mobile's best!") {
errmsg = errmsg + " - Your phone number\n";
}
if (form.os0.value != "Pickup from Toowong, Brisbane") {
// Validate "name"
if (form.name.value === "" || form.name.value === "His/her name") {
errmsg = errmsg + " - His/her name\n";
}
}
// Alert if fields are empty and cancel form submit
if (errmsg === "Oops, you're required to complete the following fields! \n") {
form.submit();
} else {
alert(errmsg);
return false;
}
}
</script>
</head>
<body>
<form name="form" action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return validate(form)">
<p class="row">
<input type="hidden" name="on0" value="Pickup and delivery" />Pickup and delivery<br />
<select name="os0" onchange="checkPickup()">
<option value="" selected >Choose</option>
<option value="Pickup from Toowong, Brisbane">Pickup from Toowong, Brisbane $1.00 AUD</option>
<option value="Brisbane +$23.60">Brisbane +$23.60 =$1.00 AUD</option>
</select>
</p>
<p class="row">Your daytime phone number<br />
<input type="text" name="phone" value="Mobile's best!" onclick="clickclear(this, 'Mobile\'s best!')" onblur="clickrecall(this,'Mobile\'s best!')" />
</p>
<p class="row">Recipient's name<br />
<input style="color: #ccc" class="name" type="text" name="name" value="His/her name" onclick="clickclear(this, 'His/her name')" onblur="clickrecall(this,'His/her name')" disabled />
</p>
<input name="custom" type="hidden" />
<input type="hidden" name="currency_code" value="AUD" />
<input class="button" type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1"> -->
</form>
</body>
</html>
This may be a simple misunderstanding of what you've written:
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
translates to the following in plain english:
If the value is NOT "Pickup from Toowong, Brisbane", enable the field, otherwise disable it.
which is equivalent to:
ONLY disable the field when the value is "Pickup from Toowong, Brisbane".
I believe the logic you're looking for is:
if (form.os0.value == "Brisbane +$23.60" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
though it might be prettier to code this with a switch statement due to the involvement of specific cases.
See DEMO
did you intend to type double equal to (==) or is the triple equal to (===) a typo in the question? Based on looking at your code, it looks to me like you need a double equal to (==) not a triple. I think triple may mean something else.

Firefox java script form

I have the following jsp code below. I am having issues with Firefox sending different parameters in the get method than Interenet Explorer. Any ideas?
Here is the get url:
Internet Explorer:
http://www.example.com/app/search/SkillSearch.do?dispatch=skillSearch2&textSearch=test&search=&searchField=test&searchType=
Firefox:
http://www.example.com/app/search/SearchPeople.do?dispatch=&textSearch=&search=&searchField=test&searchType=
<script>
function doSearch(selection,searchInfo){
// Get the Search Bar Form
var searchForm = document.getElementById('searchBarForm').firstChild;
// Get the dispatch input in the Search Bar Form
var searchFormChildren = searchForm.childNodes;
var dispatch;
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == "dispatch") {
dispatch = searchFormChildren[i];
break;
}
}
// Variable to hold search input
var searchField;
// Set form variables depending on type of search selected
if (selection.selectedIndex == "0") {
dispatch.value = "skillSearch2";
searchForm.action = "/app/search/SkillSearch.do";
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'textSearch') {
searchField = searchFormChildren[i];
break;
}
}
}
else if (selection.selectedIndex == "1") {
dispatch.value = "searchPeople";
searchForm.action = '/app/search/SearchPeople.do';
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'search') {
searchField = searchFormChildren[i];
break;
}
}
}
else if (selection.selectedIndex == "2") {
dispatch.value="search";
searchForm.action = '/app/search/LinkSearch.do';
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'search') {
searchField = searchFormChildren[i];
break;
}
}
}
searchField.value = searchInfo.value;
searchForm.submit();
}
function checkKeyPress(selection, searchInfo) {
if (window.event && window.event.keyCode == 13) {
doSearch(selection, searchInfo);
}
}
</script>
<logic:present name="SSO_TOKEN" scope="session">
<p id="searchBarForm">
<html:form action="/search/SearchPeople.do" method="get">
<input type="hidden" name="dispatch" value=""/>
<input type="hidden" name="textSearch" value="" /> <input type="hidden" name="search" value="" />
<input size="15" name="searchField" value="Search" onfocus="if (this.value == 'Search') this.value = '';" onkeypress="checkKeyPress(searchType, searchField)"/>
<select class="select" name="searchType" size="1" style="font-size: 13px;" onkeypress="checkKeyPress(searchType, searchField)">
<option value="" selected>Subject Matter Experts</option>
<option value="">Users</option>
</select>
<input class="button" type="button" value="Search" onclick="doSearch(searchType, searchField)" />
</html:form>
</p>
</logic:present>
Validate. Validate. Validate. A paragraph cannot contain a form, and different browsers appear to be recovering from that error in different ways.
Additionally, don't assume that the first element and the first child are the same. Some browsers will create a textNode consisting entirely of whitespace when you have: <foo> <bar></bar> </foo>.
David Dorward's answer is spot on. Compare IE and Firefox at http://software.hixie.ch/utilities/js/live-dom-viewer/saved/949 (which is more or less your markup, assuming you're serving up a quirks-mode document)

Categories