I'm pretty new at js programming. I'm developing an admission form as part of our project to be submitted. It's also my first time asking a question here.
I'm creating a form of validation to prevent any invalid values to be entered. I also need some optimizations at my code. If you have any suggestions to make it shorter, I'll be glad to accept your suggestion too.
I tried executing the matchCheck() function on other scenarios, but it just works fine. I also tried executing validateDate() on the console and other scenarios, but it also worked without any errors. I got an error when the functions are executed at if statements.
Here is the error message: Unknown TypeError: arrayToBeChecked.includes is not a function
I got an error at these function and if statements:
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
if (matchCheck(date[0], "null") === false)
if (validateDate(bdate) === true)
Here is the code (Excluded some of the unrelated variables and codes):
//Check Match
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
//Date Validator
//Expected Format [MM/DD/YYYY]
function validateDate(date) {
//check if the date is valid
var leapYear = date[2] % 4;
var mos31 = ["1", "3", "5", "7", "8", "10", "12"];
var mos30 = ["4", "6", "9", "11"];
var flyInv = ["30", "31"];
var fnlyInv = ["29", "30", "31"];
var mos30Inv = "31";
if (matchCheck(date[0], "null") === false) {
if (matchCheck(date[1], "null") === false) {
if (matchCheck(date[2], "null") === false) {
if (leapYear == 0) {
if (date[0] == "2") {
if (matchCheck(flyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false
}
}
else {
if (date[0] == "2") {
if (matchCheck(fnlyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
//Contact Number Validator
//Expected Format [09XXXXXXXXX]
function cnValid(nos) {
if (nos.value.length === 11) {
if(nos.indexOf("09") > -1) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
//Check for empty selects
function checkEmptySelects(el) {
var selects = document.querySelectorAll(el);
var i;
for (i = 0; i < selects.length; i++) {
if (selects[i].value == "0") {
return true;
}
else {
return false;
}
}
}
//Valid Relation Values
var vrv = ["mother", "father", "grandmother", "grandfather", "auntie", "uncle", "housemaid", "Mother", "Father", "Grandmother", "Grandfather", "Auntie", "Uncle", "Housemaid", "Aunt", "aunt", "brother", "Brother", "sister", "Sister", "cousin", "Cousin"];
//Start Review
function reviewForm() {
var letters = /^[a-zA-Z\s]*$/;
var mailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var noScFormat = /[^a-zA-Z0-9\\,\\.\s]/g;
//Perform Checks
if (checkEmptySelects("select") === false) {
if (ln.value.match(letters)) {
if (fn.value.match(letters)) {
if (mn.value.match(letters)) {
if (eml.value.match(mailFormat)) {
if (age.value >= 0) {
if (age.value <= 100) {
if (validateDate(bdate) === true) {
if (pob.value.match(noScFormat)) {
if (ca.value.match(noScFormat)) {
if (rlg.value.match(letters)) {
if (nsl.value.match(letters)) {
if (cmn.value.match(letters)) {
if (mo.value.match(letters)) {
if (cfn.value.match(letters)) {
if (fo.value.match(letters)) {
if (gn.value.match(letters)) {
if (matchCheck(vrv, rts) === true) {
if (cnValid(cn) === true) {
if (lrn.value.length === 12) {
//Submit Data to db if all of the requirements are passed.
}
else {
//Error Message;
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
The error occurs when the "arrayToBeChecked" value that is passed to the "matchCheck()" function is not an arry. To fix this, you could convert "arrayToBeChecked" to an array if it's not already an array.
function matchCheck(arrayToBeChecked, findingValue) {
// Convert arrayToBeChecked to an array if it's not already an array
if (!Array.isArray(arrayToBeChecked)) {
arrayToBeChecked = [arrayToBeChecked];
}
return arrayToBeChecked.includes(findingValue);
}
Related
I have a javascript method in a partial view .Net 6 MVC like this: After upgrading to JQuery 3.6.1 and JQuery UI 1.13.2. I am getting errors like:
Uncaught Error: cannot call methods on NumericBox prior to initialization; attempted to call method 'isNumeric'. Please suggest. Thanks.
function CompareDialog() {
var aReleased;
$(".weighting-total").NumericBox("setValue", $(".weighting").NumericBoxSum());
}
The javascript for the NumericBox and NumericBoxSum:
$.widget("Data.NumericBox", {
options: {
allowReservedValues: undefined,
readOnly: undefined,
decimalPlaces: undefined,
showZero: undefined,
allowNegative: undefined,
thousandSeperator: undefined
},
_create: function () {
this._super();
var that = this;
// Option: Allow Reserved Values
if (this.options.allowReservedValues == undefined) {
if (this.element.data("allow-reserved-values") != undefined) {
this.options.allowReservedValues = JSON.parse(this.element.data("allow-reserved-values").toLowerCase());
}
else {
this.options.allowReservedValues = false;
}
}
// Option: Read Only
if (this.options.readOnly != undefined) {
this.element.prop("readonly", this.options.readOnly);
}
// Option: Decimal Places
if (this.options.decimalPlaces == undefined) {
if (this.element.data("decimal-places") != undefined) {
this.options.decimalPlaces = parseInt(this.element.data("decimal-places"));
}
else {
this.options.decimalPlaces = 0;
}
}
// Option: Show Zero
if (this.options.showZero == undefined) {
if (this.element.data("show-zero") != undefined) {
this.options.showZero = JSON.parse(this.element.data("show-zero").toLowerCase());
}
else {
this.options.showZero = true;
}
}
// Option: Allow Negative
if (this.options.allowNegative == undefined) {
if (this.element.data("allow-negative") != undefined) {
this.options.allowNegative = JSON.parse(this.element.data("allow-negative").toLowerCase());
}
else {
this.options.allowNegative = false;
}
}
// Option: Thousand Seperator
if (this.options.thousandSeperator == undefined) {
if (this.element.data("thousand-seperator") != undefined) {
this.options.thousandSeperator = this.element.data("thousand-seperator");
}
else {
this.options.thousandSeperator = ",";
}
}
// Set client-side validation to ignore N/Avail and N/Appl values
if ($.validator.defaults.ignore.indexOf(".fd-not-available") < 0) {
$.validator.setDefaults({
ignore: $.validator.defaults.ignore + ",.fd-not-available,.fd-not-applicable"
});
}
// Define validation for hyphens
if (this.options.allowNegative) {
if ($.validator.methods["val-hyphen"] === undefined) {
$.validator.addMethod("val-hyphen", function (value, element) {
var message = $(element).data("val-number");
if (value == "-") {
return false;
}
return true;
}, $.validator.format("{0}"));
}
this.element.attr("val-hyphen", this.element.data("val-number"));
}
// Handle paste
this.element.on("paste", function (event) {
if ($(this).hasClass("fd-not-available") || $(this).hasClass("fd-not-applicable")) {
$(this).val("").removeClass("fd-not-available fd-not-applicable");
}
});
// Handle clearing of textbox
this.element.on("input", function (event) {
if ($(this).val() == "") {
$(this).removeClass("fd-not-available fd-not-applicable");
}
});
this.element.keydown(function (event) {
if (that.isReserved()) {
if (!$(this).prop("readonly") && (event.which == 8 || event.which == 46)) {
$(this).val("").removeClass("fd-not-available fd-not-applicable").select();
event.preventDefault();
}
}
});
this.element.keypress(function (event) {
if (that.element.prop("readonly")) {
event.preventDefault();
return;
}
if (event.which == 78 || event.which == 110) { // N
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotAvailable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 80 || event.which == 112) { // P
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotApplicable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 45) { // -
if (!that.options.allowNegative) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which == 46) { // .
if (that.options.decimalPlaces == 0) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which >= 48 && event.which <= 57) { // 0 - 9
if (that.isReserved()) {
$(this).val("");
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
event.preventDefault();
});
this.element.focusin(function (event) {
var value = that._internalFormat($(this).val());
$(this).val(value);
});
this.element.focusout(function (event) {
var value = that._externalFormat($(this).val());
$(this).val(value);
});
this.element.val(this._externalFormat(this.element.val()));
this.refresh();
},
_externalFormat: function (value) {
if ($.isNumeric(value)) {
if (parseFloat(value) == 0 && !this.options.showZero) {
return "";
}
else if (!ReservedValue.isReserved(value)) {
var signPart = value > -1 && value < 0 ? "-" : ""; // Required: In the following statement parseInt removes the sign for small negative numbers
var integerPart = parseInt(numeral(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)));
var fractionalPart = Big(value).minus(Big(integerPart)).abs();
var display = signPart + numeral(integerPart).format("0" + this.options.thousandSeperator + "0") +
fractionalPart.toFixed(this.options.decimalPlaces).substr(1);
return display;
}
}
return value;
},
_internalFormat: function (value) {
try {
value = value.replace(/,/g, "");
if ($.isNumeric(value)) {
if (this.options.decimalPlaces == 0) {
value = parseInt(value);
}
else {
value = Big(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)).toString();
}
}
return value;
}
catch (e) {
return value;
}
},
refresh: function () {
var value = this._internalFormat(this.element.val());
if (this.options.allowReservedValues) {
if (value == ReservedValue.NotAvailable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-applicable").addClass("fd-not-available");
}
else if (value == ReservedValue.NotApplicable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-available").addClass("fd-not-applicable");
}
else {
if (this.element.hasClass("fd-not-available") || this.element.hasClass("fd-not-applicable")) {
this.element.removeClass("fd-not-available fd-not-applicable");
}
}
}
return this;
},
setValue: function (value) {
this.element.val(this._externalFormat(value));
this.refresh();
},
getValue: function () {
return this._internalFormat(this.element.val());
},
isNumeric: function (includeReservedValues) {
includeReservedValues = includeReservedValues === undefined ? false : includeReservedValues;
if (!includeReservedValues && this.isReserved()) {
return false;
}
else {
return $.isNumeric(this.getValue());
}
},
isReserved: function (resval) {
var value = ReservedValue.parse(this._internalFormat(this.element.val()));
if (resval === undefined) {
return ReservedValue.isReserved(value);
}
else {
return value == resval;
}
},
setReserved: function (resval) {
this.element.val(resval).valid();
this.refresh();
},
getReserved: function () {
return ReservedValue.parse(this._internalFormat(this.element.val()));
}
});
$.fn.NumericBoxSum = function (blankIfNoNumerics) {
var NumericCount = 0;
var sum = 0.0;
blankIfNoNumerics = blankIfNoNumerics === undefined ? false : blankIfNoNumerics;
this.each(function () {
if ($(this).NumericBox("isNumeric")) {
sum += parseFloat($(this).NumericBox("getValue"));
NumericCount++;
}
});
if (NumericCount == 0 && blankIfNoNumerics) {
sum = "";
}
return sum;
};
I'm a beginner in JS and trying to sort some cars by their model. The models are sorted by ranking in this order (Mercedes, BMW, Jeep, Nissan). I would like it to be case-insensitive. I went about it by creating a variable for creating the desired rankings.
var modelRanking = function(car) {
if (car.model.toLowerCase() === 'mercedes') {
return 1;
} else if (car.model.toLowerCase() === 'bmw') {
return 2;
} else if (car.model.toLowerCase() === 'jeep') {
return 3;
} else if (car.model.toLowerCase() === 'nissan') {
return 4;
} else {
return 5;
}
}
function modelComparator(car1, car2) {
if (car1.modelRanking < car2.modelRanking) {
return true;
} else if (car1.modelRanking > car2.modelRanking) {
return false;
} else if (car1.modelRanking == car2.modelRanking) {
return yearComparator(car1, car2);
}
}
However the modelRanking is always returning 5.
Instead of car1.modelRanking, use modelRanking(car1) because modelRanking is a function in global scope, not a property of car1.
function modelComparator(car1, car2) {
if (modelRanking(car1) < modelRanking(car2)) {
return true;
} else if (modelRanking(car1) > modelRanking(car2)) {
return false;
} else if (modelRanking(car1) == modelRanking(car2)) {
return yearComparator(car1, car2);
}
}
I have the following code that works with other circumstances but is giving me problems I guess due to the window.locaton. Please help I need to redirect users to specific mobile pages depending on the desktop page.
function mon() {
if ($('body').is('.mon')) {
return true;
} else {
return false;
}
}
function tue() {
if ($('body').is('.tue')) {
return true;
} else {
return false;
}
}
function wed() {
if ($('body').is('.wed')) {
return true;
} else {
return false;
}
}
function detectmob() {
if (screen.width <= 800) {
return true;
} else {
return false;
}
}
if (detectmob() && mon()) {
window.location = "../m/days/mon.html";
} else if (detectmob() && tue()) {
window.location = "../m/days/tue.html";
} else if (detectmob() && wed()) {
window.location = "../m/days/wed.html";
}
It was my mistake
<body class="mon">
<script src="jquip.min.js"></script><!--increase load time instead of jquery.min-->
<script>
function mon() {
if ($('body').is('.mon')) {
return true;
} else {
return false;
}
}
function tue() {
if ($('body').is('.tue')) {
return true;
} else {
return false;
}
}
function wed() {
if ($('body').is('.wed')) {
return true;
} else {
return false;
}
}
function detectmob() {
if (screen.width <= 800) {
return true;
} else {
return false;
}
}
if (detectmob() && mon()) {
window.location = "../m/days/mon.html";
} else if (detectmob() && tue()) {
window.location = "../m/days/tue.html";
} else if (detectmob() && wed()) {
window.location = "../m/days/wed.html";
}
</script>
working fine
i'm using jquery to validate a form using ajax to check if the old password is correct then compare the new password to the confirm password input but the function always return false the submit button doesn't work at all here's the code (the returned data from ajax is correct i've checked it)
function check_pwd() {
var pass = $("#oldPWD").val();
ajax = new XMLHttpRequest();
ajax.open("POST", "ajax/check_pass.php?pass=" + pass);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
result = ajax.responseText;
if (result.indexOf('wrong') !== -1) {
alert("wrong password");
return false;
} else {
return true;
}
}
}
ajax.send(null);
}
function confirmPwd() {
var pwd1 = $("#newPWD").val();
var pwd2 = $("#newPWD2").val();
if (pwd1 !== pwd2) {
alert("do not match");
return false;
} else {
return true;
}
}
function check_form() {
if (!check_pwd() || !confirmPwd()) {
return false;
} else {
return true;
}
}
Make new password validation when the old one is already veryfied.
function confirmPwd() {
var pwd1 = $("#newPWD").val();
var pwd2 = $("#newPWD2").val();
if (pwd1 !== pwd2) {
alert("do not match");
return false;
} else {
return true;
}
}
function check_form() {
var pass = $("#oldPWD").val();
ajax = new XMLHttpRequest();
ajax.open("POST", "ajax/check_pass.php?pass=" + pass);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
result = ajax.responseText;
if (result.indexOf('wrong') !== -1) {
alert("wrong password");
return false;
} else {
confirmPwd();
}
}
}
ajax.send(null);
if (!check_pwd() || !confirmPwd()) {
return false;
} else {
return true;
}
}
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; }