retain form values onclick after javascript validation fails - javascript

This is part of an assignment. Everything that's supposed to work, already works, but there's something that bothers me. The only purpose of the code so far is to test our ability to validate from data. Anyway, right now the validate() function is attached to a submit button:
<input type="submit" value="Find Love" onclick="validate()">
When any validation fails, all the text boxes, drop downs, etc. are cleared, but I want them to retain their values and just focus on the first incorrect value (retaining their values is more important to me at this point). The actual Does that require some modification of the onclick function or a different function all together? Please help. If you need to see the javascript I can post that as well.
function validate()
{
var blnValid = true;
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!")
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!")
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!")
document.getElementById("txtAge").focus();
}
}
if(blnValid)
{
var strInput = document.getElementById("txtAge").value;
if(!isInt(strInput))
{
blnValid = false;
alert("You must enter a valid number in the age field.")
document.getElementById("txtAge").select();
}
}
if(blnValid)
{
if(document.getElementById("selUserGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
if(document.getElementById("selFindGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
blnChecked = false;
arRadio = document.forms[0].rdbAgeRange;
for (var i = 0; i < arRadio.length; i++)
{
if(arRadio[i].checked)
{
blnChecked = true;
break;
}
}
if (!blnChecked)
{
alert("You must select an age group.");
blnValid = false;
}
}
if(blnValid)
{
if(!document.getElementById("chkSkeeball").checked
&& !document.getElementById("chkAir").checked
&& !document.getElementById("chkCliff").checked
&& !document.getElementById("chkHamster").checked)
{
blnValid = false;
alert("You must select a hobby.")
}
}
return blnValid;
}
function isInt(strValue)
{
var validNums = "0123456789";
var blnIsNumber = true;
var tempChar;
for (var i = 0; i < validNums.length; i++)
{
tempChar = strValue.substr(i, 1);
if (validNums.indexOf(tempChar) == -1)
{
return false;
}
}
return true;
}
function isBlank(elementID)
{
if(document.getElementById(elementID).value.length == 0)
{
return true;
}
return false;
}

Your problem is actually your HTML. Nothing in your Javascript is going to clear the elements but because you're using onClick the form is actually submitting anyway. I assume that it probably just submits back to the page and clears everything. Instead of onClick use onSubmit in the form element:
<form method="post" action="url_of_action" onSubmit="return validate()">
If it's not valid it will prevent the form from submitting.

Missing semi-colons:
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!") //here
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!") //and here
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!") //and here
document.getElementById("txtAge").focus();
}
}

Related

Why my below javascript code in asp.net not working?

<script language="javascript" type="text/javascript">
function validate() {
summary += isvalidFirstName();
summary += isvalidMobile();
summary += checkPassword();
summary += checkEmail();
if (summary != "") {
alert(summary);
return false;
} else
return true;
}
function isvalidFirstName() {
var uid;
var temp = document.getElementById("<%=txtFirstName.ClientID %>");
uid = temp.value;
if (uid == "") {
return ("Please enter firstname" + "\n");
} else
return "";
}
function isvalidMobile() {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMob = document.getElementById(txtMobile);
if (mob.test(txtMob.value) == false) {
alert("Please enter valid mobile number");
txtMob.focus();
return false;
} else
return true;
}
function checkPassword(inputtxt) {
var pass = /^[A-Za-z]\w{7,14}$/;
if (inputtxt.value.match(pass)) {
alert("Password is correct");
return true;
} else {
alert("Wrong...!");
return false;
}
}
function checkEmail(inputtxt) {
var mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputtxt.value.match(mail)) {
return true;
} else {
alert("Please enetr a valid email id");
return false;
}
}
</script>
I have added the above javascript code inside an .ASPX page and called the function validate on button click but it is not working. Can anyone help me?

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)

Conditional valdiation of required fields

I have a page where the user enters their address. I want to make city, state and zip code required fields, but here's the catch. Either the user is required to enter both the city and the state OR they are required to enter the zip code. How do I do this javascript?
For now I have
function Form(f) {
for (var n = 0; n < f.elements.length; n++) {
if ((f.elements[n].name).indexOf("zip_code") > -1) {
var zipcode = f.elements[n].value;
if (zipcode.length == "") {
if ((f.elements[n].name).indexOf("cityname") > -1) {
var city = f.elements[n].value;
if (city.length == "") {
alert("Enter City name");
break;
}
}
if ((f.elements[n].name).indexOf("statename") > -1) {
var state = f.elements[n].value;
if (state.length == "") {
alert("Enter State name");
break;
}
}
} else {
//return true; then do something
return false;
}
} else if (zipcode.length == "") {
alert("Enter zipcode");
break;
return false;
}
}
}
Can you please try this?
function Form(f) {
var cityname = document.getElementsByName('cityname')[0].value;
var statename = document.getElementsByName('statename')[0].value;
var zip_code = document.getElementsByName('zip_code')[0].value;
if( (cityname.length==0 && statename.length==0 ) ){
if(zip_code.length==0){
alert("Enter zipcode");
return false;
}
return true;
}else if( (cityname.length==0 || statename.length==0 ) ){
if (cityname.length == 0) {
alert("Enter City name");
return false;
}else if (statename.length == 0) {
alert("Enter State name");
return false;
}
return true;
}
}
Something like this should help
if( zipcode.length){
/* validate zipcode*/
}else{
if( city.length && state.length){
}else{
/* must have city and state*/
}
}
use a variable flag.
flag = 0;
if city and state
make flag as 1
if zip
make flag as 1
if flag==0 then validation failed
else allow to submit form

How to validate multiple checkbox with javascript

I have simple page with multiple check boxes and radio buttons, This is only validating the first system check box and skipping over the next comm check box. I'm fairly new to js and I'm sure this is a simple fix. Any assistance would be appreciated thanks!!!
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
return false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
return false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
return false;
}
return true;
}
How can I get this to validate multiple check boxes? Will I also need to apply the same fix for multiple sets of radio buttons?
I think the problem is that you're returning from the function too soon. Try this:
function test() {
var valid = true;
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
valid = false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
valid = false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
valid = false;
}
return valid;
}
This way, it validates everything you want, alerts what you need, and returns the validity like you expect.
Another option, which instead of alerting for each validation, you can do something like this:
function test() {
var valid = true;
var messages = [];
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
messages.push('Please select System Access');
valid = false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
messages.push('Please choose a Department');
valid = false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
messages.push('Please select Comm Access');
valid = false;
}
if (messages.length > 0) {
alert(messages.join("\n"));
}
return valid;
}
In this case, you get one alert at the end with all the errors. Might be nicer for the user.
<script defer="defer" type="text/javascript"><!--function validateForm(formElement) {
if (formElement.first_name.value.length < 2)
return focusElement(formElement.first_name,
'Please enter a First Name that is at least 2 characters long.');
if (formElement.last_name.value.length < 2)
return focusElement(formElement.last_name,
'Please enter a Last Name that is at least 2 characters long.');
if (formElement.model_id.value.length < 7)
return focusElement(formElement.model_id,
'Please enter a Model ID that is at least 7 characters long.');
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
return false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
return false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
return false;
}
return true; } function focusElement(element, errorMessage) {
alert((errorMessage.length > 0) ? errorMessage :
'You did not enter valid data; Please try again');
if (element.select) element.select();
if (element.focus) element.focus();
return false; } function countSelected(formElement, inputType, inputName) {
if (inputType == null) inputType = 'checkbox';
var returnValue = 0;
for (var loopCounter = 0; loopCounter < formElement.length; loopCounter++) {
var element = formElement.elements[loopCounter];
if (element.type == inputType && element.checked == true) {
if (inputName.length > 0)
if (element.name == inputName)
returnValue++;
else
returnValue++
}
}
return returnValue; } function countSelectedOptions(selectElement) {
var returnValue = 0;
for (var loopCounter = 0; loopCounter < selectElement.options.length; loopCounter++)
if (selectElement.options[loopCounter].selected == true)
returnValue++;
return returnValue;
}
//-->

Javascript showing alert without refreshing the page

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

Categories

Resources