Simplifying IF/ELSE IF/ELSE Block - javascript

I'm creating my own validation code. I need to separate the if statements per input box for the error to show at the same time. I noticed that if it's on same if block, only the first error will show. Any way to simplify my code?
flag = 0;
//first if
if (first_name.length == 0) {
flag = 0;
$("label[for='firstname'").text('This field is required').css("display", "inline-block");
} else if (!first_name.match(name_regex)) {
flag = 0;
$("label[for='firstname'").text('Firstname must be composed of letters only').css("display", "inline-block");
} else if (first_name.length < 3) {
flag = 0;
$("label[for='firstname'").text('3 letters are required for lastname').css("display", "inline-block");
} else {
flag = +1;
$("label[for='firstname'").hide();
}
//second if
if (last_name.length == 0) {
flag = 0;
$("label[for='lastname'").text('This field is required').css("display", "inline-block");
} else if (!last_name.match(name_regex)) {
flag = 0;
$("label[for='lastname'").text('Lastname must be composed of letters only').css("display", "inline-block");
} else if (last_name.length < 2) {
flag = 0;
$("label[for='lastname'").text('2 letters are required for lastname').css("display", "inline-block");
} else {
$("label[for='lastname'").hide();
flag += 1;
}
//third if
if (validateEmail(email)) {
if (data.result) {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Email exists').css("display", "inline-block");
} else {
$("input#userEmail").css("border-color", "#e3e3e3");
$("label[for='email'").hide();
flag += 1;
}
} else {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Please input a valid email address').css("display", "inline-block");;
}
//fourth if on verification success
if (flag == 3) {
alert("All validation succeded!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Just extract it into a function:
function validate(inputName, labelName, minLetters, regex){
const el = $(inputName);
const label = $(labelName);
if(!el || !!label) throw "validate: el not found";
if(!el.val()){
label.text("You need to fill in this!");
return false;
}
if(regex && !el.val().test(regex)){
label.text("The input contains invalid chars!");
return false;
}
if(minLetters && el.val().length < minLetters){
label.text("to short!");
rerurn false;
}
return true;
}

I would suggest to make the validation routine more generic. Please see following solution (note: untested):
function validate(funcName, minLength) {
if (this[funcName].length == 0) {
$("label[for='"+funcName+"'").text('This field is required').css("display", "inline-block");
} else if (!this[funcName].match(name_regex)) {
flag = 0;
$("label[for='"+funcName+"'").text(funcName +' must be composed of letters only').css("display", "inline-block");
} else if (this[funcName].length < minLength) {
$("label[for='"+funcName+"'").text(minLength + ' letters are required for ' + funcName).css("display", "inline-block");
} else {
$("label[for='"+funcName+"'").hide();
return true;
}
return false;
}
if (validate("firstname", 2)
&& validate("lastname", 3)
&& validateEmail(email)
) {
// everything seems to be OK.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

My approaches will be :
Have individual If blocks for each validations by which all the validations will be checked. And build/append the validation error message on each check.
Write if else blocks within a function. That function can be called for each fields being validated. And the function will return validation error message for each invokation which can be appended into a single string.

Related

I have a javascript that checks if my form is valid and it stops checking after a certain field

So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.

How to check if switch is true or not to hide the div?

I have some problem when I check the function validation, I need when checking all the cassis is true hide the parent div * errors message *
var error_pass = false;
$('#pass').focusout(function(){
check_pass();
error_pass = false;
if(error_pass !== true){
console.log('its showing!');
}else{
$('.test').fadeOut('522');
}
});
function check_pass() {
var fpass= $('#pass').val();
switch(error_pass = true){
case(fpass.length < 6 ? $('#pass-error-message3').css('color','red'):$('#pass-error-message3').css('color','green') ):
$('#pass-error-message3').show();
case(fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1 ? $('#pass-error-message4').css('color','red') : $('#pass-error-message4').css('color','green')):
$('#pass-error-message4').show();
case(fpass.search(/\d/) == -1 ? $('#pass-error-message2').css('color','red'):$('#pass-error-message2').css('color','green')):
$('#pass-error-message2').show();
default:break;
}
}
Use if else statements like this
function validation() {
var error = false;
if (fpass.length < 6) {
error = true;
$('#pass-error-message3').css('color', 'red').show();
} else {
$('#pass-error-message3').css('color', 'green');
}
if (fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1) {
error = true;
$('#pass-error-message4').css('color', 'red').show();
} else {
$('#pass-error-message4').css('color', 'green')
}
if(fpass.search(/\d/) == -1){
error = true;
$('#pass-error-message2').css('color','red').show();
}else{
$('#pass-error-message2').css('color','green');
}
if(error === false){
hideParentDiv(); // Here hide the div
}
}
Much cleaner approach

jConfirm message cannot work properly

The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.

Input button never appears when javascript detects form completed

I'm making a register page using HTML, CSS and JS and Java servlet etc. I have a monitorer() function which checks if the user has finished inputting everything before making the register button visible. But now everything works, but somewhere am getting screwed over and the button never comes back..
my button in reg.html :
<input type="submit" value="Register" class="btnSub" id="btnReg" style="visibility:hidden;"/>
javascript function monitorer()
function monitorer() {
var btnReg = document.getElementById("btnReg");
btnReg.style.visibility = "hidden";
var flag = true;
if (document.getElementById("fname").value.length >= 3) {
if (document.getElementById("lname").value.length >= 3) {
if (valiDate(document.getElementById("dob"))) {
if (document.getElementById("USN").value.length == 10) {
if (document.getElementById("passw").value.length > 5) {
var ticks = document.getElementsByClassName("checker"), i = 0;
for (i = 0; i < ticks.length; i++) {
if (ticks.item(i).innerHTML == "✔") {
alert("i val = " + i);
continue;
} else {
flag = false;
break;
}
}
}
} else {
flag = false;
document.getElementById("USN").focus();
}
} else {
flag = false;
document.getElementById("dob").focus();
}
} else {
flag = false;
document.getElementById("lname").focus();
}
} else {
flag = false;
document.getElementById("fname").focus();
}
if (flag == true) {
btnReg.style.visibility = "visible";
} else if(flag == false) {
btnReg.style.visibility = "hidden";
}}
And to help you get as good a picture as you can, a screenshot
See - all the ticks are there, the first name, last name etc are having value.length >=3 but still the register button doesn't show..
Also, I have put the monitorer() method in every input's "onBlur", "onChange" events.
Here is a link to my html file >>> reg.html
and please let me know if i can improve anything?

How to change this IF to allow selection between two numbers only?

I am using a jQuery script and the main part is below. It allows me to select up to 4 items. Until there are 5 selections made, there is an error message.
How can I change this so that the error message appears if the choices are less than 2 and more than 5, and the success message is shown when the choices are between them?
if ($(this).multiselect("widget").find("input:checked").length > 5) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
You can get the number of checked items in to a local variable and then use a compound if statement that does multiple comparisons on it:
var checkedItemsLength = $(this).multiselect("widget").find("input:checked").length;
if(checkItemsLength < 2 || checkItemsLength > 5 ) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
function doSomeChecking() {
// assuming 'warning is a reference to some div or span
var warning = $('#warning');
var numChecked = $(this).multiselect("widget").find("input:checked").length;
if (numChecked > 5) {
warning.addClass("error").removeClass("success").html("You cannot check more than five boxes!");
return false;
} else if (numChecked < 2) {
warning.addClass("error").removeClass("success").html("You must check at least two boxes.");
return false;
}
warning.addClass("success").removeClass("error").html("Life is good.");
return true;
}
var selections = $(this).multiselect("widget").find("input:checked");
if(selections.length < 2) {
warning.addClass("error").removeClass("success").html("You have to check atleast two checkboxes!");
return false;
} else if (selections.length > 5) {
warning.addClass("error").removeClass("success").html("You can not check more then five checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
if(foo < 2 || foo > 5){
//do something
}else {
//do something else
}

Categories