What I want is when a user enters in a phone number into an input field, my cloud code will validate it. Below is what I have so far.
Parse.Cloud.beforeSave("Contact", function (request, response) {
var Contact = Parse.Object.extend("Contact");
var query = new Parse.Query(Contact);
query.equalTo("PhoneNo", request.object.get("PhoneNo"));
query.first({
success: function (object) {
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(object.value)) {
response.error("Enter a valid phone number.");
return false;
} else {
response.success();
}
},
error: function (error) {
response.error("Could not validate phone number.");
}
});
});
I have used filterPhone below on the client side and that validates the phone number but I cant seem to get it to work on the cloud.
var phone = document.getElementById('Pno');
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(phone.value)) {
alert('Please provide a valid phone number');
return false;
}
Thanks in advance.
Thomas.
I don't understand the need for a query. I believe you want something like this:
Parse.Cloud.beforeSave("Contact", function (request, response) {
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(request.object.get("PhoneNo"))) {
response.error("Enter a valid phone number.");
} else {
response.success();
}
});
Am I missing something?
-Bob
Related
I've developed a simple login system in JS. When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code. Thanks in advance =)
I leave here the piece of code:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
}
else if (user != arr[f][0] && pass == arr[f][1]) {
alert("Your username is incorrect");
}
else {
alert("Unnexistant account");
}
}
}
Add break; after each document.write or alert statements.
Your instinct is correct, and a for loop is probably not ideal here. It is hard to read and debug and it's also kind of ugly. If you want to stick with it, the other answers show you how.
Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.
const map = new Map();
arr.map(e => m.set(e[0], e[1]));
try {
if (map.get(user) === pass) {
document.write("welcome back " + user + ", we missed you.");
} else {
// although this might be too much info from a security standpoint.
document.write("incorrect password");
}
} catch (e) {
document.write("could not find user.");
}
If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
return; // exit from the function since we've found an account
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
return; // exit from the function since we've found a username match
}
}
// couldn't find match, alert
alert("Your account does not exist.");
}
I'm new to js and firebase. I'm trying to use firebase database for a custom login by using my own table called users. I have used a for each loop to go through the data. But the else part is executed multiple time because of this. I need to break the loop so it won't happen.
This is my data:-
{"users" : [ {
"userId" : "1",
"username" : "admin",
"password" : "admin",
"type" : "admin"
}, {
"userId" : "2",
"username" : "cashier",
"password" : "cashier",
"type" : "cashier"
}]
}**
This is the code I wrote:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users = childSnapshot.child('username').val();
var pass=childSnapshot.child('password').val();
if(txtuser==users && txtpass==pass){
var type=childSnapshot.child('type').val();
if(type=="admin"){
location.href="admin.html";
}
else if(type=="cashier"){
location.href="cashier.html";
}
}
else{
error=true;
}
});
});
if(error==true)
{
window.alert("Invalid Credentials");
location.href="index.html";
}
}
Password Authentication
Instead of using your method of storing authentication details in the database, use the Sign in a user with an email address and password flow.
However, because you are using usernames not emails, append your storage bucket domain to the username (which will normally be PROJECT_ID.appspot.com).
So your "admin" and "cashier" users would become "admin#PROJECT_ID.appspot.com" and "cashier#PROJECT_ID.appspot.com". For the sake of email authentication, these are valid email addresses, even though they don't have inboxes.
You can then use firebase.auth() across your web app to manage your user's access control to pages like "admin.html" and "cashier.html".
Note: If you ever send out email to your users, make sure to omit emails that match "*#PROJECT_ID.appspot.com"
Answering the question
WARNING: Do not authenticate this way. Please use above method.
Passwords should never be stored in plain text
Passwords should never be stored in plain text
Users should never have access to another user's credentials in any database
For the sake of answering the question, you could use the following code:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
firebase.database().ref('users').orderByChild('username').equalTo(txtuser).once('value')
.then(function(snapshot) {
if (!snapshot.hasChildren()) {
throw "username not found";
} else if (snapshot.numChildren() != 1) {
throw "duplicate usernames";
}
// only one child at this point, so only called once
snapshot.forEach(function(childSnapshot) {
if (pass != childSnapshot.child('password').val()) {
throw "password mismatch";
}
var type=childSnapshot.child('type').val();
if(type=="admin") {
location.href = "admin.html";
} else if(type=="cashier") {
location.href = "cashier.html";
} else {
throw "unknown user type";
}
})
})
.catch(function(error) { // catches any errors thrown by promises
location.href = "index.html";
});
}
In the above code, each throw is caught by the Promise returned by the Firebase query. You can read up on Promises here.
Just check if error is set to true inside the .forEach and use return to "break" out:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users, pass;
if (error) { return; } // <-- "break" the "loop"
users = childSnapshot.child('username').val();
pass = childSnapshot.child('password').val();
if(txtuser == users && txtpass == pass){
var type=childSnapshot.child('type').val();
if(type == "admin"){
location.href="admin.html";
}
else if(type == "cashier"){
location.href="cashier.html";
}
} else {
error = true;
}
});
if(error) {
window.alert("Invalid Credentials");
location.href="index.html";
}
});
}
I am trying to query the user twice (more than once in general), but everything gets printed out together and the first response get processed by both functions. I believe this has to do with the asynchronous nature of node.js. Can you please point me towards module that would take care of this for me or an implementation in prompt module? Thank you.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
});
var prompt2 = require('prompt');
prompt2.start();
console.log("Enter a number again: ");
prompt2.get(['number1', 'number2'], function(err, result) {
if (Number(result.number1) > Number(result.number2))
console.log("The first input is bigger");
else if (Number(result.number1) == Number(result.number2))
console.log("Both inputs are equal");
else
console.log("The second input is bigger");
});
I am not sure if you actually need both prompt instances. I think you can achieve what you want with only one prompt and just calling get second time within the first get's callback.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
console.log("Enter a number again: ");
prompt.get(['number'], function(err, result) {
if (result.number < 20)
console.log("small");
else if (result.number < 50)
console.log("medium");
else
console.log("large");
});
});
I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.
I take full advantage of GMail's wildcard feature (username+wildcard#gmail.com). Unfortunately it seems that most developers don't understand that + is valid in an email address. This makes trying to unsubscribe a real chore sometimes.
Take TicketMaster for example... immediately you notice that they didn't even bother escaping the email address, so the text field defaults to "user wilcard#gmail.com". Not a problem, we can just add the + manually. Once Submit is clicked, you'll notice the validation stops you right in your tracks. What now?
Most users would have to further contact TicketMaster and attempt to explain the situation. I opened up FireBug to investigate. That's when I noticed this whopping 74 line email validation function with so much redundancy it's ridiculous. My favorite check is on line 20, informing the user that his/her email cannot have more than one #. Unreal. My second favorite part is the TWO regular expressions used!
Imagine... someone was paid money for this... and by the looks of it, they were paid by the line count.
//Validates the email
function validateOptoutEmail(object) {
var emailStr = object.value;
if(emailStr == '' || emailStr == null) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else if(Trim(emailStr).length == 0) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else {
var atcount=0;
for(var i=0;i<emailStr.length;i++) {
if(emailStr.charAt(i)=='#') atcount++;
}
if(atcount>1) {
alert('Invalid email. Email cannot have more than one #');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('.') == -1) {
alert('Invalid email. Email must have one dot');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('..')!= -1) {
alert('Invalid email. Email cannot have consecutive dots');
object.value = '';
object.focus();
return false;
}
var dotpos=0;
for(var i=dotpos;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if(ichar=='.') dotpos=i;
}
for(var i=dotpos+1;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if((!isNaN(ichar)) || (ichar == '_')) {
alert('Invalid email. Email cannot have numbers or _ after dot');
object.value = '';
object.focus();
return false;
}
}
var pattern2=/^([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
var pattern1=/^[0-9a-zA-Z\-\_.]+#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (pattern1.test(emailStr)) {
if(pattern2.test(emailStr)) {
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
}
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
}
I eventually just put a break point in FireBug and changed the value of the email address passed into the validation function. From there everything worked fine...
All that said, how can we get the word out there that + is valid in an email address? Too often, I'm unable to use the email address that I want to use for certain web sites because developers simply aren't aware of what constitutes a valid email address.
Point them at the rfc:
https://www.rfc-editor.org/rfc/rfc5322#page-10
3.2.3 states "+" is a valid atom