Validate function to check file extension from database - javascript

I need to validate the extension of an uploading file in js.I have successfully created a fuction like as follows.
function FileExtension_Validate(txt)
{
if( !txt.match(/\.(pdf)|(doc)|(PDF)|(DOC)|(docx)|(DOCX)$/)) { return false; } else {return true; }
}
But now my situation is, i have a database field which have data as follows
pdf,doc,PDF,DOC,docx,DOCX
Now i need to create a function based on the data from database.Is there any possible solution.Please help me..?

I solved it as follows..
function FileExtension_Validate(txt)
{
//alert(txt);
var extension=document.getElementById('extension').value;
var piece = extension.split(',');
var split=extension.split(',').length
var flag=0;
//alert(piece[0]);
for (var i = 0; i <split; i++)
{
var test=piece[i];
//alert(test);
if( txt!=test) { flag++;}
//else {return true; }
}
// alert(flag);
if(flag==split)
{
return false;
}
else{
return true;
}
in extension i have passed the extension of the uploade file

Related

how to compare two different length objects in for loop?

I have tried to create a login function which when the user enters the vaild name and password then it will print "welcome user " else "invalid user".
In my code it accepts one username and password and showing invalid for another one...I cant understand why its showing like this...
code:
<script>
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name+inp[i].mail);
console.log(out[j].Name+out[j].mail);
if((inp[i].Name== out[j].Name)&&
(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome
user";
}
else{
document.getElementById("out1").innerText="Invalid
user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
</script>
find fiddle here:
https://jsfiddle.net/xp1Lrbdh/#&togetherjs=d0wTznLFgu
The issue is because of the iteration you are doing even after finding if entered user is valid user. In simple terms, putting a break statement solves your problem.
See the snippet below:
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name, inp[i].mail);
console.log(out[j].Name, out[j].mail);
if((inp[i].Name== out[j].Name)&&(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome user";
break;
}
else{
document.getElementById("out1").innerText="Invalid user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
NOTE: This is not a best practice to verify credentials also avoid using var, use let, const instead
const accounts = [
{
name:"dhanam",
mail:"dhanamram98#gmail.com"
},
{
name:"alamelu",
mail:"alamu98#gmail.com"
}
]
function output() {
const nameNode = document.getElementById("input1")
const mailNode = document.getElementById("input2")
const name = nameNode.value
const mail = mailNode.value
const found = accounts.find(a => a.name === name && a.mail === mail)
if (found) {
document.getElementById("out1").innerText="welcome user";
} else {
document.getElementById("out1").innerText="Invalid user";
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);

How can I use Global variable across multiple functions in JavaScript?

I have a piece of code which is intended to check the permission level and group membership of a use and launch a dialog box if the user has the correct permissions to access that section of the site.
function bindSettingsButton() {
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
}
function RequestNewSite() {
var HasPermission = false;
var isGroupMember = false;
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
CheckUserPermissions();
}
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
this.userGroups = this.currentUser.get_groups();
clientContext.load(this.userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
}
function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group = groupsEnumerator.get_current();
if(group.get_title() == "Create Site OptOut") {
isMember = true;
this.isGroupMember = true;
break;
}
}
}
function OnQueryFailed()
{
alert("Couldn't check user group membership. Please contact to resolve this issue.");
}
function CheckUserHasEditPermissions() {
context = new SP.ClientContext.get_current();
web = context.get_web();
this._currentUser = web.get_currentUser();
this._theList = web.get_lists().getByTitle('siterequests');
context.load(this._currentUser);
context.load(this._theList, 'EffectiveBasePermissions')
context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
}
function onPermissionsSuccessMethod(sender, args) {
if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
{
this.HasPermission = true;
}
else
{
this.HasPermission = false;
}
}
function onPermissionsFailureMethod()
{
alert("Couldn't check permissions. Please contact to resolve this issue.");
}
function CheckUserPermissions() {
if(this.isGroupMember == true)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
}
else if(this.HasPermission == false)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact .");
}
else
{
showDialogue();
document.getElementById("next-stage").focus();
}
}
Unfortunately when it reaches the end this section the variables HasPermission and isGroupMember are still undefined so the dialogue launches automatically for every user.
I have a feeling I have misused the .this keywords and this is a scoping error but I am not expert enough in JS to know for certain or be able to fix it. Can anyone tell me exactly what I've done wrong and how to fix it please?
You are performing async functions, which means the rest of the code will keep executing even though the stuff you have started first are not completed yet.
You will have to call the CheckUserPermissions after onPermissionsSuccessMethod and the OnQuerySucceeded function has completed.
In addition to this the HasPermission and isGroupMember variables are local to the RequestNewSite function, which means they are out of the scope of the CheckUserPermissions function.
var HasPermission = false;
var isGroupMember = false;
var CompletedCallbacks = 0;
function bindSettingsButton() {
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
}
function RequestNewSite() {
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
}
function CheckCurrentUserMembership() {
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
this.userGroups = this.currentUser.get_groups();
clientContext.load(this.userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded, OnQueryFailed);
}
function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group = groupsEnumerator.get_current();
if(group.get_title() == "Create Site OptOut") {
isMember = true;
isGroupMember = true;
break;
}
}
CompletedCallbacks++;
CheckUserPermissions();
}
function OnQueryFailed()
{
alert("Couldn't check user group membership. Please contact SPCOE#capita.co.uk to resolve this issue.");
}
function CheckUserHasEditPermissions() {
context = new SP.ClientContext.get_current();
web = context.get_web();
this._currentUser = web.get_currentUser();
this._theList = web.get_lists().getByTitle('siterequests');
context.load(this._currentUser);
context.load(this._theList, 'EffectiveBasePermissions')
context.executeQueryAsync(Function.createDelegate(this, this.onPermissionsSuccessMethod), Function.createDelegate(this, this.onPermissionsFailureMethod));
}
function onPermissionsSuccessMethod(sender, args) {
if (this._theList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))
{
HasPermission = true;
}
else
{
HasPermission = false;
}
CompletedCallbacks++;
CheckUserPermissions();
}
function onPermissionsFailureMethod()
{
alert("Couldn't check permissions. Please contact SPCOE#capita.co.uk to resolve this issue.");
}
function CheckUserPermissions() {
if(CompletedCallbacks != 2) return;
if(isGroupMember == true)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE#capita.co.uk.");
}
else if(HasPermission == false)
{
alert("You do not have permission to create sites. If you believe you should have access to this functionality, please contact SPOCOE#capita.co.uk.");
}
else
{
showDialogue();
document.getElementById("next-stage").focus();
}
}
This code should work.
$("#mt-ngw-personalsettings").on("click", function() {
RequestNewSite();
});
If you are expecting to use RequestNewSite as a constructor, you need to use new to allocate it. If you call as a function no object (and thus state) is created.
Additionally all members of the type need to be created explicitly on this.
So
function RequestNewSite() {
var HasPermission = false;
var isGroupMember = false;
CheckCurrentUserMembership();
CheckUserHasEditPermissions();
[...]
Needs to be
function RequestNewSite() {
this.HasPermission = false;
this.isGroupMember = false;
this.CheckCurrentUserMembership();
this.CheckUserHasEditPermissions();
[...]

Using REGEX inside an IF function

I am trying to validate zip codes using an if function with a regex. Can this be done? I currently just have the if function making sure the zip code is 5 numbers.
below is the regex i want to use
(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)
Can someone show me where and how i would add this to the if function below?
var value = $(this).val();
if( value.length<5 || value==$(this).attr('id') ) {
$(this).addClass('error');
error++;
} else {
$(this).addClass('valid');
}
var ZipCode = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (ZipCode.test(98800)) {
// true
} else {
// false
}
Try this
Try this
var filter = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (!filter.test($(this).attr('id').value)) {
$(this).addClass('error');
error++;
}
else
{
$(this).addClass('valid');
}

asynchronous call to return a value?

I am bulding a table that either shows a play button or a stop button. (and some other stuff)
for(var i = 0; i < result.length; i++){
var current = result[i].split("$");
if (CheckRunning(current[0])){
t = t + "<tr><td><img alt='stop' id='img"+i+"' src='stop.png' onclick='ChangeButton(\"img"+i+"\");'/>";
} else {
t = t + "<tr><td><img alt='play' id='img"+i+"' src='play.png' onclick='ChangeButton(\"img"+i+"\");'/>";
}}
The problem here is the CheckRunning method. It opens a database which is an asynchron method. I cant simply do a return true/false. So whats the solution? anyway, here is the code for it:
var tabel;
var running = false;
function CheckRunning(tabel){
this.tabel = "tabel"+tabel+"";
var db = window.openDatabase(this.tabel, "1.0", this.tabel, 1000000);
db.transaction(checkrunningDB, checkerrorCB);
console.log(this.running);
return this.running;
}
function checkrunningDB(tx) {
tx.executeSql('SELECT max(id), sluttime FROM '+this.tabel, [], checkrunningSuccess, checkerrorCB);
}
function checkrunningSuccess(tx, results) {
if (results.rows.item(0).sluttime != null){
this.running = false;
} else{
this.running = true;
}
}
function checkerrorCB(err) {
this.running = false;
console.log(err);
}
Pass a callback function to CheckRunning:
CheckRunning(current[0], function(isRunning){...})
...
function CheckRunning(tabel, callback)
{
var isRunning = null; // we don't know yet
....
callback(isRunning);
}
It's similar to your tx.executeSql function which takes checkRunningSuccess as a callback. In that case the function name is hard coded as checkRunningSuccess, you could do the same in checkRunning.
By the way, if this is a public webapp running SQL queries makes you vulnerable to SQL injection attacks.

How validate max number of files before upload?

Hi I'm using the upload file plugin and I need to validate the number of files added before upload the file...Something like this
$('#fileupload').bind('fileuploadadd', function (e, data) {
filestoupload++;
var numOfDivs = $('.request').size();
if (numOfDivs < filestoupload) {
upload = false; // Is just an example.
}
});
This worked for me, on your fileupload definition add a beforesend, and there do the validation
var maxfiles=3;
$('#fileupload').fileupload(({
url: postFileUrl,
submit: function (event, files) {
//check for max files THIS IS WHERE YOU VALIDATE
//console.log(files.originalFiles.length);
var fileCount = files.originalFiles.length;
if (fileCount > maxFiles) {
alert("The max number of files is "+maxFiles);
throw 'This is not an error. This is just to abort javascript';
return false;
}
}
});
that throw is by far not elegant, if you happend to implement this and find a way to avoid that please make me know (for now is necesary or it will display the error alert for each file uploaded)
use data.files.length
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
var fileCount = data.files.length;
if (fileCount < filestoupload) {
upload = false;
}
});

Categories