Form validation JavaScript not working - javascript

My form validation function is not working properly. The error msg displayed in the innerHTML element goes away as soon as it appears, like the page is being refreshed.I am new in javascript. I don't know whet seems to be the problem.
<script type="text/javascript">
function validate(form) {
var user = form.txtUsername;
var institute = form.txtinstitute;
var email = form.txtemail;
var pass1 = form.pwdpassword1;
var pass2 = form.pwdpassword2;
var check = "";
check = validateFilled(pass2);
check = validateFilled(pass1);
check = validateFilled(email);
if (check == true) {
check = validateEmail(email);
}
check = validateFilled(institute);
check = validateFilled(user);
if (checked == false) {
return false;
}
//return true;
}
function validateFilled(control) {
if (control.value.length == 0) {
document.getElementById(control.id).nextSibling.innerHTML = "* required";
document.getElementById(control.id).focus();
return false;
}
return true;
}
function validateEmail(control) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!(re.test(email.value))) {
document.getElementById(email.id).nextSibling.innerHTML = " *invalid email";
document.getElementById(email.id).focus();
return false;
}
return true;
}
</script>

check = validateFilled(pass2);
check = validateFilled(pass1); //overrides check above
check = validateFilled(email); //overrides check above
if (check == true) {
check = validateEmail(email);//overrides check above
}
if (check == true) {
check = validateEmail(email);//overrides check above
}
check = validateFilled(institute);//overrides check above
check = validateFilled(user);//overrides check above
So if any of those are false, the other checks under it will make it true. Bad design....
You need to only set check to false if the validation fails....

Related

How can ı make capitalization checker with array some and map function?

I use OOP system. I have one product list add project and ı want to capitalization check. I know two solution for problem but doesn't work.
For example, I entered a product called "bag" and again I want the same product not to be capitalized. Different letters such as "bag" and "Bag" or "BAG" should not be written in capital letters. how can ı fix this? Thanks advance for answer. (You just need to answer one of the two solutions.) Full code: https://codepen.io/BerkayAkgurgen/pen/bGBNojw
// Some Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (todos.some(a => a.trim().toLowerCase() == newTodoValuee)) {
console.log("sdaas");
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}
// Map Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
var words = todos.map(w => w.toLowerCase());
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (words.includes(productName)) {
e.preventDefault();
console.log("Aynı Todo");
nameInput.value = "";
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}
Ok, your code is huge, makes sense I guess, so I'll just give you a function you can use to only return common letters from a given text element(so that you can work with it)
The idea of how the function is used is that you store all values as lowercase FROM THE INPUT and do checks when INPUT IS ALREADY LOWERED
var x=document.getElementById('x')
function lowerCaseInput(elem){return elem.value.toLowerCase()}
var obj={}
document.getElementById('b')
.addEventListener('click',function(ev){
var input=lowerCaseInput(x)
if(obj[input]){alert(`Error: "${input}" already exists`)}
else{obj[input]=1; console.log(obj)}
})
<input id="x" />
<button id="b">add value</button>

Why does this form keep on submitting even if it fails the validation?

I am new to javascript. I would like someone to explain to me why this form keeps getting submitted even if it fails the validation? I am not allowed to use any validation plugins hence I wrote several functions for validation.
/* EMAIL VALIDATION */
let validateEmailInput = (anEmail) => {
let emailRegex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (anEmail.value.search(emailRegex) !== -1 || anEmail.value.match(emailRegex)) {
document.getElementById("errorOutput1").innerText = "";
return true;
} else {
document.getElementById("errorOutput1").innerText = "Invalid email!";
anEmail.focus();
return false;
}
}
/* RADIO VALIDATION */
let validateRadioInput = (name) => {
let radios = document.getElementsByName("part1_radio");
let isCheckedRadio = false;
let numRadioChecked = 0;
let radioChosen;
for (let i = 0; i < radios.length && !isCheckedRadio; i++) {
if (radios[i].checked) {
numRadioChecked++;
document.getElementById("errorOutput2").innerText = "";
radioChosen = radios.item(i).id;
isCheckedRadio = true;
}
} //end for
if (numRadioChecked === 0) {
document.getElementById("errorOutput2").innerText = "Please select one season!";
isCheckedRadio = false;
}
return isCheckedRadio;
}
/* CHECKBOX VALIDATION */
let validateCheckboxInput = (name) => {
let checkboxGroup = document.getElementsByName("part1_checkbox");
let isCheckedCheckbox = false;
let numCheckboxChecked = 0;
let checkboxChosen;
for (let i = 0; i < checkboxGroup.length && !isCheckedCheckbox; i++) {
if (checkboxGroup[i].checked) {
numCheckboxChecked++;
document.getElementById("errorOutput3").innerText = "";
checkboxChosen = checkboxGroup[i];
isCheckedCheckbox = true;
} else {
// if (numCheckboxChecked === 0) {
document.getElementById("errorOutput3").innerText = "Please check at least one country!";
isCheckedCheckbox = false;
}
} // end for
return isCheckedCheckbox;
}
/* SELECT/OPTIONS VALIDATION */
let validateSelectInput = (aSelection) => {
let selectGroup = document.getElementsByName("part1_select");
let isCheckedSelect = false;
let numCheckedSelect = 0;
let selectedVar;
if (!selectGroup.value) {
document.getElementById("errorOutput4").innerText = "Please choose one!";
isCheckedSelect = false;
} else {
isCheckedSelect = true;
selectedVar = selectGroup.value;
}
return isCheckedSelect;
}
This function is called inline like this:
<form id="myForm_part1" name="myForm_part1"action="someemailhere" method="post" onsubmit="validateForm(this.form);" novalidate>
I need help understanding why this happens.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function() {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
return false;
}
});
}
There is an issue with the onsubmit handler. Try changing
onsubmit="validateForm(this.form);"
to
onsubmit = "return validateForm(this.form);"
Without the return statement the submit handler, which is a function compiled from the attribute value, returns undefined because it doesn't have a return statement.
Use preventDefault() to stop submission if validation fails.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function(event) {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
event.preventDefault();
}
});
}

How do I set a javascript variable inside a for loop to be used afterwards

So, I'm creating a login form, and when certain criteria aren't met to continue after the form, I am setting a variable to be tested after I've tested all the criteria. IF that variable ($cantcontinue) is set to 'true' I want to send a console message with the criteria that isn't met. Here is my code:
function testfields() {
// Ask if logging in or Creating Account
//Logging In:
if (document.getElementById("tEmail").style.display != "unset") {
var loginelements = ["Username", "Password"];
var text = "";
var i;
for (i = 0; i < loginelements.length; i++) {
//Check all fields are full:
if (document.getElementById(loginelements[i]).value == "") {
document.getElementById(loginelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(loginelements[i] + " is not set,")
} else {
document.getElementById(loginelements[i]).style.background = '#f7f7f7'
}
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
//Create a new Account:
} else {
var createelements = ["Username", "Password", "tEmaili", "tConfirmi"];
var text = "";
var i;
for (i = 0; i < createelements.length; i++) {
//Check all fields are full:
if (document.getElementById(createelements[i]).value == "") {
document.getElementById(createelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(createelements[i] + " is not set,")
} else {
document.getElementById(createelements[i]).style.background = '#f7f7f7'
}
}
//If passwords Match
if (document.getElementById("Password").value != document.getElementById("tConfirmi").value) {
var cantcontinue = true;
document.getElementById("tConfirmi").style.background = '#ff6060'
document.getElementById("tConfirmi").value = ''
console.log(" Passwords didn't Match,");
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
}
}
$cantcontinue !== cantcontinue;//....
Also
if (cantcontinue != true) {
equals:
if (!cantcontinue) {
Sidenote: Please don't use "$" unless you're using jQuery. It reminds me of PHP ( brrrrr...)

Any better way to declare variables avoiding repetition of code?

Here is the js code which i am trying to use. I don't like the same code repeating again and I couldn't help myself to do this in a better way.
$(function(){
$('[data-behavior~=quick-reject]').on("click", function(){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if((some_reasons.val() === "") && ( some_action === "reject")){
var errorReason = "Please select a reason";
form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if(some_action === "verify"){
some_reasons.hide();
}else{
some_reasons.show();
}
});
});
You could just make a little utility function, something like.
function getVars(that) {
var form = $(that).closest("[data-behavior~=modal-footer]").find("form");
return {
form: form,
some_action: form.find("#some_actions").val(),
some_reasons: form.find("[data-behavior~=escalation-reason-select-box]")
}
}
$('[data-behavior~=quick-reject]').on("click", function(){
var v = getVars(this);
if((v.some_reasons.val() === "") && ( v.some_action === "reject")){
var errorReason = "Please select a reason";
v.form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
v.form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var v = getVars(this);
if(v.some_action === "verify"){
v.some_reasons.hide();
}else{
v.some_reasons.show();
}
});

Javascript function stops working when adding int

I'm making system where questions can be answered trough a select box system. It works so far
function changedValue(vraagId) {
currentId = document.getElementById(vraagId+1).value;
valueId = document.getElementById(vraagId).value;
if (currentId == "") {
document.getElementById(valueId+1).disabled = true;
document.getElementById(valueId+2).disabled = true;
document.getElementById(valueId+3).disabled = true;
document.getElementById(valueId+4).disabled = true;
document.getElementById(vraagId+1).value = valueId;
}
else {
document.getElementById(valueId+1).disabled = true;
document.getElementById(valueId+2).disabled = true;
document.getElementById(valueId+3).disabled = true;
document.getElementById(valueId+4).disabled = true;
document.getElementById(currentId+1).disabled = false;
document.getElementById(currentId+2).disabled = false;
document.getElementById(currentId+3).disabled = false;
document.getElementById(currentId+4).disabled = false;
document.getElementById(vraagId+1).value = valueId;
}
}
function removeValue(vraagId) {
currentId = document.getElementById(vraagId+1).value;
document.getElementById(currentId+1).disabled = false;
document.getElementById(currentId+2).disabled = false;
document.getElementById(currentId+3).disabled = false;
document.getElementById(currentId+4).disabled = false;
document.getElementById(vraagId+1).value = "";
if (vraagId == 'vraag1') {
document.getElementById('antwoord01').selected = true;
}
if (vraagId == 'vraag2') {
document.getElementById('antwoord02').selected = true;
}
if (vraagId == 'vraag3') {
document.getElementById('antwoord03').selected = true;
}
if (vraagId == 'vraag4') {
document.getElementById('antwoord04').selected = true;
}
}
But now I want to add a system that enables a button when all questions are answered. I've come up with a system that uses an int. As soon as a question is answered, it adds 1. As soon as a question is unanswered, it removes 1. However, when I add int beantwoord = 0; to my script it gives me the error
Uncaught ReferenceError: changedValue is not defined
How can I fix this?
JavaScript is dynamically-typed (variable can hold different types of data), so the following statement will throw an error:
int someVar = 1;
Instead, declare your variable using var, e.g.
var someVar = 1;

Categories

Resources