Global variable setting fails in JavaScript validation - javascript

I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.

if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.

This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks

Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console

Related

html - use onsubmit and action together

I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
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!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.

Return false from Function within function - Javascript Form Validation

I made a function which validates a form and works fine but I now want to break it down into 3 separate functions.
I now have a function which is called by the form being submitted which declares some arrays and runs the three functions. When it was all one big function the various if statements that found errors would return false; which would then go back to the form and stop it sending.
However now that I've got functions within a function I can't figure out how to get that message 'false' back to the form.
Below is the function called by the form submit button followed by the main function it calls.
I tried creating an empty variable which is returned instead of false which is then is assigned the value false by the validateSignup function but it didn't work.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
passMatch();
genderCountryCheck()
}
function validateText(formNumber, numberElements, errorSpansArrayName, regexErrorArrayName, regexArrayName)
{
for (x = 0; x<numberElements; x++)
{
var spanName = errorSpansArrayName[x];
var textError = document.getElementById(spanName);
var y=document.forms[formNumber].elements[x];
if (!y.value)
{
errorMessage(0,spanName,x);
return false;
}
if(!regexArrayName[x].test(y.value)){
textError.innerHTML = regexErrorArrayName[x];
return false;
}
}
UPDATE:
Thanks for your responses. I have found a solution that seems to work for me.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var returnValidateText=validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
var returnPassMatch = passMatch();
var returnGenderCountry = genderCountryCheck();
if (returnValidateText || returnPassMatch || returnGenderCountry === false)
{
return false;
}
else{
return true;
}
}
If you call the function it returns a value
var formIsValid = function validateText(....)
should do the trick.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var formIsValid = false;
formIsValid = validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
formIsValid = passMatch();
formIsValid = genderCountryCheck()
}
One way is to just check the individual function returns directly and return based on that
if (!validateText(0,6,errorSpansArray, regexErrorArray, regexArray)) {
return false;
}
if (!passMatch()) {
return false;
}
if (!genderCountryCheck()) {
return false;
}
Although it's shorter to use a single conditional
return
validateText(0,6,errorSpansArray, regexErrorArray, regexArray) &&
passMatch() &&
genderCountryCheck();
In javascript return false means false will be returned as value where the method is called. So you need something like
If(validateText()){
return true;
}
And similarly rest of the code.

validating an email with javascript

I am learning about simple javascript form validation and I am just curious why my email validation is not working. I am trying to grab the information from the email input field and run my function with the RegEx in it. Any help would be appreciated.
fiddle demo: http://jsfiddle.net/6SWj4/
(function(){
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
// console.log(email.test(str));
//
// if(email.test(str) == true){
// console.log("true");
// }else{
// console.log("false");
// }
myform.onsubmit = function(e){
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
var validateField = function(inputName){
if (inputName.name === 'f_email'){
var pattern = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var emailVal = new RegExp(pattern);
//You will need to create an else-if statement for each input field id. The
// format will be similar to the above IF statement.
}else{
console.log("not valide");
}
var pass = emailVal.test(inputName);
console.log(pass);
var errorMsg = inputName.nextSibling.nextSibling.nextSibling.nextSibling;
if (!pass || inputName.value.length < 2){
errorMsg.style.display='block';
inputName.style.backgroundColor = 'red';
} else if (pass && inputName.value.length > 5){
errorMsg.style.display='none';
inputName.style.backgroundColor = 'green';
} else {
errorMsg.style.display='none';
inputName.style.backgroundColor = 'white';
};
};
})(); // end wrapper
Your problem stems from getting the value of the input on page load, not after user has entered anything. Try:
myform.onsubmit = function(e){
/* get value withing submit handler*/
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
ALso flaw in validateField(). Argument expected is inpuname but you are passing in email input value
You have many errors in the code. First what i said you on the comments, you have to do the document.getElementById("f_email").value; inside of onsubmit function. You are also declaring variables inside something and using it out of it, for example emailVal that you declare inside the if. That cannot work, you have to declare it before the if. check with the javascript console these little errors.

Only first part of Javascript function being called

I'm having problems with this function I've made, the first part is called fine but after the first if statements nothing else is being called. I've used JSfiddle, but it doesn't indentify a serious problem.
I usually work with PHP not JS so I'm wondering if there is something simple I am missing here?
function validatequestion(form){
var e = document.getElementById("chooseqtype");
var strQtype = e.options[e.selectedIndex].value;
if(strQtype == "default"){
alert("Please select a question type");
return false;
}
if(strQtype == "textquestion"){
fail = validatetextq(form.textquestiondesc.value)
if(fail == "") return true
else {
alert(fail);
return false;
}
}
if(strQtype == "videoquestion"){
fail = validatevideoq(form.videoquestiondesc.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
//everything above works, after this point nothing seems to get called
var a = document.getElementById("chooseatype");
var strAtype = a.options[a.selectedIndex].value;
if(strAtype == "textanswer"){
//get the value of the number of text answers select box
var t = document.getElementById("choosetextnumber");
//put the value in variable strQtype
var strTextno = t.options[t.selectedIndex].value;
if(strTextno == "2tanswers"){
fail = validatetexta1(form.textanswer1.value)
fail += validatetexta2(form.textanswer2.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
}
}
If strQtype can only be one of the 3 values you are testing for then there is no way you can ever get to the second part of your code because you always return from each of those if statements.
EDIT:
What you need to do is not return when fail == "". Since you're just returning true I assume you don't need to return a value, just verify that the validation was successful. What you should do then is only test for failure, e.g. if (! fail=="" ) (syntax is prob wrong, javascript is not my first lang.) and in that case do your alert.
Or you could always just write 3 different functions, one to test each menu item, which is what I would probably do.

Invalid left-hand side in assignment for simple login script

I have to build a simple login script for a js class.
I cannot get the loop to work. Everytime I type in any info it gives me "Invalid left-hand side in assignment"
When the login button is clicked the getData function gets the values of the boxes then passes them to the logon function that checks against the array. That's where the script stops. If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
What am I doing wrong?
<script type="text/javascript">
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass = userLogins[i].password && user = userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
= is the assignment operator
== is the equality operator
You're confusing the two. You want the latter. Otherwise, your assigning the value which results returns the value itself (often a true value).
Per the comments, there's also the strict equality operator. For the difference between == and === this answer will blow your mind.

Categories