Validation Error in javascript - javascript

Validation doesn't work correctly. when we fill at any one field of these, it goes to function call
if ((name == "") && (uname == "") && (password1 == "") && (password2 == "") && (imei == "")) {
alert("Enter Necessary Fileld");
} else if (password1 == password2) {
registerDetails(name, uname, password1, managerId, address1, address2, city, state, country, postcode, number, email, imei, simCard);
} else {
alert("Password Doesn't match");
}

I guess, you wanted to use || instead of &&.
|| would mean, that any field must be empty to not validate, while && means what all fields must be empty.

Try this.
if ((name == "") || (uname == "") || (password1 == "") || (password2 == "") || (imei == "")) {
alert("Enter Necessary Fileld");
} else if (password1 == password2) {
registerDetails(name, uname, password1, managerId, address1, address2, city, state, country, postcode, number, email, imei, simCard);
} else {
alert("Password Doesn't match");
}

Change
if ((name == "") && (uname == "") && (password1 == "") && (password2 == "") && (imei == "")) {
alert("Enter Necessary Fileld");
}
to this so that it will be executed if anyone of the fields are null.
if ((name == "") || (uname == "") || (password1 == "") || (password2 == "") || (imei == "")) {
alert("Enter Necessary Fileld");
}

&& stands for conjunction, so only when all conditions are true, conjunction is true. Because your conditions check if elements are empty, in fact, you check if no one of these variables are empty.
Change && into ||, which stands for disjunction.

Related

Javascript needs to prevent blanks from being entered

The following Javascript is attached to a field form (on change ) it is supposed to ensure that if the user clicks on a button then 'off site' will populate in activity_type. And if not then '95 Modifier' will appear. In addition this form sheet has a field I have checked 'required' yet what is happening is the user is able to enter blanks for activity type. Is there a way within this javascript to then not allow a blank to be entered?
if (getFormElement('activity_type_id').toUpperCase()=='EE641670-8BE3-49FD-8914-030740D9DE72'
&& getFormElement('actual_location').toUpperCase()!='5E74C25C-6363-46BE-B030-16216B364F5A')
{
setFormElement('is_off_site',true);
} else
{
setFormElement('is_off_site',false);
}
{
setFormElement('is_off_site',false);
}
For your requirement custom function might solve your issue. It might cover almost your all primary scenarios. I have tried my best to update an answer with the best possibilities.
Please review it.
function isEmpty(inputValue) {
if(typeof inputValue === 'string' && (inputValue === '0' || inputValue === 'false' || inputValue === '[]' || inputValue === '{}' || inputValue === '')){
return true;
}else if(Array.isArray(inputValue) === true){
return inputValue.length === 0 ? true : false;
}else if(Array.isArray(inputValue) === false && (typeof inputValue === 'object' && inputValue !== null) && typeof inputValue !== 'undefined' && typeof inputValue !== null){
return Object.keys(inputValue).length === 0 ? true : false;
}else if(typeof inputValue === 'undefined'){
return true;
}else if(inputValue === null){
return true;
}else if(typeof inputValue === 'number' && inputValue === 0){
return true;
}else if(inputValue === false){
return true;
}else if(inputValue.length > 0 && inputValue.trim().length === 0){
return true;
}
return false;
}
console.log("isEmpty(' '): ",isEmpty(' '));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty([]): ",isEmpty([]));
console.log("isEmpty({}): ",isEmpty({}));
console.log("isEmpty(): ",isEmpty());
const nullValue = null;
console.log("isEmpty(null): ",isEmpty(nullValue));
console.log("isEmpty(0): ",isEmpty(0));
console.log("isEmpty(false): ",isEmpty(false));
console.log("isEmpty('0'): ",isEmpty('0'));
console.log("isEmpty('false'): ",isEmpty('false'));
console.log("isEmpty('[]'): ",isEmpty('[]'));
console.log("isEmpty('{}') ",isEmpty('{}'));
console.log("isEmpty(''): ",isEmpty(''));
console.log("isEmpty('0.0'): ",isEmpty(0.0));

Console log for foreach javascript didn't show up

I've been trying to work on some validation in javascript, just a simple one. But, the error can't show up in the console log. If all the inputs are correct, it will show the "Registration success text" but in the other side, it won't show any of the error text. But it somehow still can get the focus function to the wrong input, only the error texts that are not showing up in the console. I am so confused. Can you guys help me? I'd appreciate that.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
if(name.value === ''){
error.push("Name is required.");
name.focus();
return false;
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
name.focus();
return false;
}
if(uname.value === ''){
error.push("Username is required.");
uname.focus();
return false;
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
uname.focus();
return false;
}
if(email.value === ''){
error.push("Email is required.");
email.focus();
return false;
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
return false;
}
if(passw.value === ''){
error.push("Password is required.");
passw.focus();
return false;
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
confpassw.focus();
return false;
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
if(region.value == 0){
error.push("Region is not selected");
region.focus();
return false;
}
if(gender.value == 0){
error.push("Gender is not selected");
gender.focus();
return false;
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
termss.focus();
return false;
}
if(error.length == 0){
alert("Registration Success!");
} else{
for(var i=0; i<error.length; i++){
console.log(error.length[i]);
};
}
}
You are returning too early so it is never reaching your consoles. You are focusing on multiple fields.
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
You are also doing console.log(error.length[i]); instead of console.log(error[i]);.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
let firstFailedField = null;
const setFirstFailedField = (field) => {
if (!firstFailedField) firstFailedField = field;
};
if(name.value === ''){
error.push("Name is required.");
setFirstFailedField(name);
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
setFirstFailedField(name);
}
if(uname.value === ''){
error.push("Username is required.");
setFirstFailedField(uname);
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
setFirstFailedField(uname);
}
if(email.value === ''){
error.push("Email is required.");
setFirstFailedField(email);
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
setFirstFailedField(email);
}
if(passw.value === ''){
error.push("Password is required.");
setFirstFailedField(passw);
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
setFirstFailedField(confpassw);
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
setFirstFailedField(confpassw);
}
if(region.value == 0){
error.push("Region is not selected");
setFirstFailedField(region);
}
if(gender.value == 0){
error.push("Gender is not selected");
setFirstFailedField(gender);
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
setFirstFailedField(termss);
}
if(error.length == 0){
alert("Registration Success!");
return true;
}
error.forEach((err) => (console.log(err)));
if (firstFailedField && typeof firstFailedField.focus === 'function') firstFailedField.focus();
return false;
}

HTML Form won't submit after validaiton with Javascript

I have questions regarding form submitting in HTML with Javascript.
My Javascript is as follows:
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
alert("Your name cannot be blank");
}
if (b == null || b == "") {
alert("Enter a valid email address.");
}
if (c == null || c == "") {
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
alert("Must select an Issue.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (g == null || g == "") {
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
alert("Preferred time must follow the format set.");
}
return false;
}
And this is my form with its attributes in HTML:
<form name="myForm" onsubmit="return validateForm()" method="post" action="confirm.html" novalidate="novalidate" >
What happens is that when I click the Submit button after filling in all the requirements(so everything does not return false) , the form won't submit itself.
After reading around regarding return false, I tried adding else{ return true; } but all it does is submit my form without validation at all.
What do I do to make it work with only Javascript and/or HTML? Thank you!
At the end of the submission function, you are returning:
return false;
}
No matter if the validation was successful or not. This prevents the form from submitting. Make sure you are using return true here and correctly validate using a flag and then if the flag is true, return false.
You have already a flag isValid. Replace the above line with:
return isValid;
}
You need to check if your inputs have passed your tests.
You can do that by using your var isValid.
All you need to do is set isValid to false if one of your conditions was not met, and then return isValid.
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
isValid=false;
alert("Your name cannot be blank");
}
if (b == null || b == "") {
isValid=false;
alert("Enter a valid email address.");
}
if (c == null || c == "") {
isValid=false;
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
isValid=false;
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
isValid=false;
alert("Must select an Issue.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (g == null || g == "") {
isValid=false;
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
isValid=false;
alert("Preferred time must follow the format set.");
}
return isValid;
}

My validation script does not work properly

function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username==null || username=="" && password==null || password=="");
{
alert("Please enter username and password");
return false;
}
else ( username == "james1" && password == "j1j22j3j" )
{
alert ("Login successfully");
window.location = "http://www.dtrekrun.com/training.html"; // Redirecting to other page.
return false;
}
}
I'm trying to validate the username/password and show an alert. But it is not working for me.
Didn't you see any error in the console?
Remove the semicolon at the end of this line:
if ( username==null || username=="" && password==null || password=="");
Else don't take arguments, else if does ! Replace
else ( username == "james1" && password == "j1j22j3j" )
by
else if ( username == "james1" && password == "j1j22j3j" )
use this
if ( username==null || username=="" && password==null || password=="")
instead of
if ( username==null || username=="" && password==null || password=="");
and
else ( username == "james1" && password == "j1j22j3j" )
by
else if ( username == "james1" && password == "j1j22j3j" )
Hope you got success
Just remove semicolon after if ( username==null || username=="" && password==null || password=="");

JavaScript conditions

If someone could point out what I'm doing wrong I'd be eternally grateful! I can't seem to get the right combination of parenthesis - how to I combine multiple conditions in one statement?? Obviously I don't expect anyone to modify the code below, I just want to show what I'm trying to achieve.
If someone can explain the logic to me that'd be great
Thanks
function ChangeButton()
{
if
((document.forms[0].IPR.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].SURN.value == "") && (document.forms[0].GEND.value == "") && (document.forms[0].DOB.value == "") && (document.forms[0].CRIM.value == "") && (document.forms[0].ETHC.value == "") && (document.forms[0].DSBC.value == "") && (document.forms[0].MARK1.value == "") && (document.forms[0].NATC.value == "") && (document.forms[0].COBC.value == "") && (document.forms[0].COD.value == "") && (document.forms[0].FIVE.value == "") && (document.forms[0].PERM.value == "") && (document.forms[0].VISF.value == "") && (document.forms[0].USD.value == "") && (document.forms[0].HAD1.value == "") && (document.forms[0].HAD3.value == "") && (document.forms[0].HTEL.value == "") && (document.forms[0].HAEM.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].REF1TIT.value == "") && (document.forms[0].REF1ORG.value == "") && (document.forms[0].REF1POS.value == "") && (document.forms[0].REF1AL1.value == "") && (document.forms[0].REF1AL3.value == "") && (document.forms[0].REF1AL5.value == "") && (document.forms[0].REF1EMA.value == "") && (document.forms[0].DISC.value == ""))
&&
((document.forms[0].PERM.value == "") && (document.forms[0].FIVE.value == "N"))
&&
((document.forms[0].AGNT.value == "") && (document.forms[0].USD.value == "Y"))
&&
((document.forms[0].CSTRT.value == "") && (document.forms[0].USD.value == "N") && (document.forms[0].CENDD.value == "") && (document.forms[0].CAD1.value == "") && (document.forms[0].CAD3.value == "") && (document.forms[0].CAD4.value == "") && (document.forms[0].CAPC.value == "") && (document.forms[0].CTEL.value == ""))
&&
((document.forms[0].AWDB.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].FEES.value == "Private Funds Self or Family") && (document.forms[0].AWDS.value == ""))
&&
((document.forms[0].RESEARCH.value == "Y") && (document.forms[0].RESSRT.value == "") && (document.forms[0].RESMOA.value == "") && (document.forms[0].RESAR.value == "") && (document.forms[0].RESDIS.value == ""))
{
document.getElementById('submitbutton').className = 'enabled';
}
else {
document.getElementById('submitbutton').className = 'disabled';
}
}
I see
...&&... document.forms[0].FIVE.value == ""
...&&... document.forms[0].FIVE.value == "N"
This never be true
EDIT
I think you must change approach, try something like this:
function ChangeButton()
{
var frm = document.forms[0];
var neverEmpty = ['field1','field2','field3'];
var mustBe = {field3:'Y', field4:'N'};
var status = 'ok';
for(var i = 0; i<neverEmpty.length; i++) {
if(frm[neverEmpty[i]] == '') {
status = 'ko';
break;
}
}
for(myField in mustBe) {
if(frm[myfield] != mustBe[myField]) {
status = 'ko';
break;
}
}
document.getElementById('submitbutton').className = status=='ok'? 'enabled' : 'disabled';
}
you don't close the brackets
if (document.forms[0].IPR.value == "" && document.forms[0].FNM1.value == "" && ect...)
it's that simple
You need one more set of parentheses around the whole lot i.e. if (a == b) { .. }
As far as I can see, you don't need any parentheses here (except for those that are required by if syntax).
if(document.forms[0].IPR.value == "" && document.forms[0].FNM1.value == "" &&
document.forms[0].PERM.value == "" && document.forms[0].FIVE.value == "N" &&
...
) {
document.getElementById('submitbutton').className = 'enabled';
} else {
document.getElementById('submitbutton').className = 'disabled';
}
Give the input elements that must be non-empty a "class" attribute. Then find all those elements using that instead of writing that insanely ugly code.
You need 1 more paren before and before the first curly brace everything if ( ... ) { ... }
Here is the corrected code.
function ChangeButton()
{
if
((document.forms[0].IPR.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].SURN.value == "") && (document.forms[0].GEND.value == "") && (document.forms[0].DOB.value == "") && (document.forms[0].CRIM.value == "") && (document.forms[0].ETHC.value == "") && (document.forms[0].DSBC.value == "") && (document.forms[0].MARK1.value == "") && (document.forms[0].NATC.value == "") && (document.forms[0].COBC.value == "") && (document.forms[0].COD.value == "") && (document.forms[0].FIVE.value == "") && (document.forms[0].PERM.value == "") && (document.forms[0].VISF.value == "") && (document.forms[0].USD.value == "") && (document.forms[0].HAD1.value == "") && (document.forms[0].HAD3.value == "") && (document.forms[0].HTEL.value == "") && (document.forms[0].HAEM.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].REF1TIT.value == "") && (document.forms[0].REF1ORG.value == "") && (document.forms[0].REF1POS.value == "") && (document.forms[0].REF1AL1.value == "") && (document.forms[0].REF1AL3.value == "") && (document.forms[0].REF1AL5.value == "") && (document.forms[0].REF1EMA.value == "") && (document.forms[0].DISC.value == "")
&&
((document.forms[0].PERM.value == "") && (document.forms[0].FIVE.value == "N"))
&&
((document.forms[0].AGNT.value == "") && (document.forms[0].USD.value == "Y"))
&&
((document.forms[0].CSTRT.value == "") && (document.forms[0].USD.value == "N") && (document.forms[0].CENDD.value == "") && (document.forms[0].CAD1.value == "") && (document.forms[0].CAD3.value == "") && (document.forms[0].CAD4.value == "") && (document.forms[0].CAPC.value == "") && (document.forms[0].CTEL.value == ""))
&&
((document.forms[0].AWDB.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].FEES.value == "Private Funds Self or Family") && (document.forms[0].AWDS.value == ""))
&&
((document.forms[0].RESEARCH.value == "Y") && (document.forms[0].RESSRT.value == "") && (document.forms[0].RESMOA.value == "") && (document.forms[0].RESAR.value == "") && (document.forms[0].RESDIS.value == "")))
{
document.getElementById('submitbutton').className = 'enabled';
}
else {
document.getElementById('submitbutton').className = 'disabled';
}
}
USE and IDE, it will make ur life simple.. Cheers to Eclipse IDE :)

Categories

Resources