form validation with radio buttons and specific errors - javascript

I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.

Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}

you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}

You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.

Related

how can I fix my form validation

I have a problem with my code and I would appreciate if you help me. The problem is - when you fill in all inputs in the form correctly, the script removes attribute "disabled" from the submit button but for example if you clear all fields after filling in the forms, submit button will be able to submit the form, but it have to back attribute "disable". how can I fix it?
//validation name
document.callbackform.name.onkeyup = function() {
var name = document.callbackform.name.value;
if (name === "") {
document.callbackform.name.removeAttribute("class", "ready");
document.getElementById("callError").style.display = "block";
document.getElementById("calllErrorTwo").style.display = "none";
} else {
document.getElementById("callError").style.display = "none";
var pattern = new RegExp("^[а-я]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.getElementById("calllErrorTwo").style.display = "block";
document.callbackform.name.removeAttribute("class", "ready");
} else {
document.getElementById("calllErrorTwo").style.display = "none";
document.callbackform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.callbackform.phone.onkeyup = function() {
var name = document.callbackform.phone.value;
if (name === "") {
document.callbackform.phone.removeAttribute("class", "ready");
document.getElementById("calltelError").style.display = "block";
document.getElementById("calltelErrorTwo").style.display = "none";
} else {
document.getElementById("calltelError").style.display = "none";
var pattern = new RegExp("[- +()0-9]+");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.getElementById("calltelErrorTwo").style.display = "block";
} else {
document.getElementById("calltelErrorTwo").style.display = "none";
document.callbackform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.callbackform.onkeyup = function() {
var a = document.callbackform.name.getAttribute("class");
var c = document.callbackform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("subCallback").removeAttribute("disabled");
document.getElementById("subCallback").style.cursor = "pointer";
} else {
document.getElementById("subCallback").setAttribute("disabled");
document.getElementById("subCallback").style.cursor = "not-allowed";
}
};
Simple fix. .setAttribute("disabled"); doesn't work as disabled is a property, not an attribute, as it does not have a value. You simply need to use .disabled = true; as shown:
document.getElementById("subCallback").disabled = true;
It will also be good to use the following to remove the disabled property:
document.getElementById("subCallback").disabled = false;
.
Remember, setAttribute() always requires two arguments, the second argument being the attribute value.

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

Could someone explain why my functions are not working?

So I'm very new to JavaScript and I'm trying a very simple enter text and check it. It doesn't seem to work the way I want it to. I want all of the inputs to go through the checkInputs. After All of them are 100% I want it to check if hoursWorked and horlyRate are numbers above 0. It seems to just move on to the checkNumberValidation without checking if all inputs are filled.
I got:
function checkNumbersValidation(field){
if( isNaN(field) ) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
var test = false;
do{
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
}else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}else {
tests = true;
}
}while (test = false)
}
function handelCalcButtonClicked (e) {
var passFirstTests = false;
var textFields = ["fullName", "hoursWorked", "hourlyRate"];
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
checkInputs(field);
}
if( **something** ) {
var numberFields = ["hoursWorked", "hourlyRate"]
for ( var i = 0; i < numberFields.length; i++ ) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
clearly I don't know what I'm doing. In the function handelCalcButtonClicked I'm not sure how to move on the the next part (the part Saying something). Any help would be nice!
Inside checkNumbersValidation you need to do the isNan call on field.value, not field:
if( isNaN(field.value) )
If you want to know if all of your fields have gone through checkInputs and have passed, you will need checkInputs to return whether or not each field has passed:
function checkInputs(field) {
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
return false;
} else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return false;
}
return true;
}
This will allow you to know if all fields have passed the check:
var passedAllChecks = true;
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
passedAllChecks = checkInputs(field) && passedAllChecks;
}
if(passedAllChecks) {
/* do number validation stuff */
}
What about this:
function checkNumbersValidation(field) {
if (isNaN(field)) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
return;
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
var textFields = ["fullName", "hoursWorked", "hourlyRate"],
numberFields = [ "hoursWorked", "hourlyRate"],
i,
field;
for (i = 0; i < textFields.length; i++) {
field = document.getElementById(textFields[i]);
checkInputs(field);
}
for (i = 0; i < numberFields.length; i++) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
or:
function checkInput(field, isnumber) {
if (!field) return;
if (isnumber === true && isNaN(field)) {
field.value = "Must be a number";
field.focus("");
return;
}
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return;
}
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
checkInput(document.getElementById('fullName');
checkInput(document.getElementById('hoursWorked', true);
checkInput(document.getElementById('hourlyRate', true);
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});

Error: '0.type' is null or not an object in javascript

I am getting the error below when I click the button that calls the JavaScript to do the validation. The strange thing is that everything was working before but I am not what happened now. If I select to ignore this error:
Error: '0.type' is null or not an object
then the code works fine but I get the error first then it asks me if i want to debug it, if i select No then the code works fine. Please help. thanks
it seems the code stops at this line:
if (areas[0].type == "textarea") {
but here is my entire code:
<script type ="text/javascript">
function Validate_1() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
//var inputs = gridView.rows[i].getElementsByTagName('input');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
// areas[i].focus();
// areas.[i].style.backgroundColor = "red";
}
return flag;
}
// document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
</script>
var areas = gridView.rows[i].getElementsByTagName('textarea');
getElementsByTagNane does not return null, the length would be zero
So your if check needs to change.
if (selects != null && areas != null)
should be
if (selects.length && areas.length)

Disable submit until form is filled javascript

I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit
For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }

Categories

Resources