javascript, looping fields and validating - javascript

I'm using below code to check some form fields and render datatable table on a button click. My intention is to stop the table from being rendered if any of the fields are empty. Apparently return false inside the loop is not working.
Is this the correct way to accomplish? any better ways?
$('#advance_search').click(function(){
var ds = $('.advance_search .filter_field');
$.each(ds, function(index, value){ //this loop checks for series of fields
if ($(this).val().length === 0) {
alert('Please fill in '+$(this).data('label'));
return false;
}
});
dt.fnDraw(); //shouldn't be called if either one of the field is empty
});

If you look carefully, your return false is inside the $.each callback function, so it returns false for the caller of that function, not the "main function" you are in.
Try this:
$('#advance_search').click(function(){
var ds = $('.advance_search .filter_field'), valid = true;
$.each(ds, function(index, value){ //this loop checks for series of fields
if($(this).val().length === 0) {
alert('Please fill in '+$(this).data('label'));
return (valid = false); //return false and also assign false to valid
}
});
if( !valid ) return false;
dt.fnDraw(); //shouldn't be called if either one of the field is empty
});

You could add a control variable to prevent the dt.fnDraw() from being called:
$('#advance_search').click(function(e){
e.preventDefault();
var check = 0, // Control variable
ds = $('.advance_search .filter_field');
$.each(ds, function(index, value){ //this loop checks for series of fields
if($(this).val().length === 0) {
check++; // error found, increment control variable
alert('Please fill in '+$(this).data('label'));
}
});
if (check==0) { // Enter only if the control variable is still 0
dt.fnDraw(); //shouldn't be called if either one of the field is empty
}
});

Related

Global variable setting fails in JavaScript validation

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

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.

Looping over attributes in validation fails to stop set of attribute

Normally in my backbone validation, I have a crazy amount of if() statements, as I've seen in many other code samples as well. Validation is pretty much a crap shoot in backbone; however, the if() way seems to work. I want to clean up the code a bit and wrote some code that does return error which should stop backbone from saving the attribute, but it doesn't!
OLD Code that works
validate : function(attr){
if(attr.firstName){
var defaultValue = 'first name',
value = attr.firstName.toLowerCase();
if(value == defaultValue){
return 'error';
}
}
}
NEW code that doesn't work
//My default strings from another place
MyApp.strings.defaults = {
firstName : 'first name'
}
//Model Validate function
validate : function(attr){
jQuery.each(attr, function(key, value){
var defaultValue = MyApp.strings.defaults[key];
if(defaultValue){
defaultValue = jQuery.trim(defaultValue.toLowerCase());
if(value == defaultValue){
console.log(value, defaultValue); //fires, and outputs both as being the same
return 'error';
}
}
});
}
Are you not allowed to loop over the attributes in Backbone validation?
You are not returning any value from the validate method, you were returning 'error' from the each() callback method, not from validate
//My default strings from another place
MyApp.strings.defaults = {
firstName : 'first name'
}
//Model Validate function
validate : function(attr){
var error;
jQuery.each(attr, function(key, value){
var defaultValue = MyApp.strings.defaults[key];
if(defaultValue){
defaultValue = jQuery.trim(defaultValue.toLowerCase());
if(value.toLowerCase() == defaultValue){
console.log(value, defaultValue); //fires, and outputs both as being the same
error = 'error';
return false;
}
}
});
return error;
}

Jquery loop form to check for all empty fields then execute a function

I'm trying to loop form to check for empty field and then execute and function. I'm currently using something like this below that I found on this website but what is happening that the each loop check 1 field and see 1 that not empty and still execute else function. I think I need to check all at once then execute next function. How could I achieve this?
if($('.enter-info--ownerInfo .req').val() != "") {
alert("Empty Fields!!")
} else {
run this function
}
Thanks...
Use filtering, it is easy:
var anyFieldIsEmpty = $("form :input").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if (anyFieldIsEmpty) {
// empty fields
}
DEMO: http://jsfiddle.net/Lz9nY/
$('.enter-info--ownerInfo .req').each(function() {
if ($(this).val() == "")
{
alert("empty field : " + $(this).attr('id'));
}
});
Start by selecting all your fields:
var fields = $('.enter-info--ownerInfo .req')
Then filter them down to the ones with an empty value:
fields.filter(function() {
return this.value === '';
});
Then check the length property of the resulting object. If it's equal to 0 then all fields have a value, otherwise you execute your function.
if(fields.length === 0) {
// no empty fields
}
else {
// empty fields
}
You can use a loop and flag:
var valid = true;
$('.req').each(function () {
if ($(this).val() == '') {
valid = false;
return false;
}
});
if (valid) {
// all fields are valid
}
You can use .filter method to reduce the elements to those matching your criteria:
if $('.enter-info--ownerInfo .req').filter(function () {
return $.trim($(this).val()) == ""
}).length > 0) {
alert("One or more fields are empty")
} else {
// run this function
}

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.

Categories