How can I return the var validEmails
to checkform()
. It's undefined
right now.
<script type="text/javascript">
function checkfile(form) {
var reader = new FileReader();
reader.onload = function(e) {
var emails = e.target.result;
var validEmails = parseEmails(emails);
return validEmails;
};
var formFiles = form.files[0];
reader.readAsText(formFiles);
function parseEmails(emails) {
var obj = Papa.parse(emails, { skipEmptyLines: true });
var valid = 1;
$.each(obj.data, function(i, v) {
var email = v[0].trim();
valid = validEmail(email);
});
return valid;
};
function validEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
};
}
function checkform(form) {
console.log( checkfile( document.getElementById('recipient_csv') ) );
}
</script>
<form method="post" action="/" enctype="multipart/form-data" onSubmit="return checkform(this);">
<input id="recipient_csv" type="file" name="recipient_csv" />
</form>
validEmails variable is within the scope of the onload function. Either defined it out the function or remove "var" ( which would make it global variable).
You should check the variables scope of javascript http://www.w3schools.com/js/js_scope.asp