validate a user registration form - javascript

I have a user registration form. I already use validation to check if all fields are filled. I need to validate email and mobile number using javascript and alert using an alertbox if its not valid. Please help
the code is
var name = $("#name").val();
var inst = $("#inst").val();
var email = $("#email").val();
var mobile = $("#mobile").val();
var dataString = 'name='+ name + '&inst='+ inst + '&email='+ email +'&mobile='+ mobile;
if(name==''|| inst=='' || email=='' || mobile=='')
{
alert("Please Enter all the Fields");
}
else
{ //rest of code comes here

var emailRe = /^\w+([\.\-]?\w+)*#\w+([\.\-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;
var phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var email_address = $('#email').val();
var phone_number = $('#phone').val();
if(emailRe.test(email_address) === false){
alert(email_address + ' is invalid');
}
if(phoneRe.test(phone_number) === false){
alert(phone_number + ' is invalid');
}
Reference: Regular Expressions Field Validation

Related

How can I validate email,firstname and lastname?

I try to validate firstname,lastname and email taken by user and return true if its valid or return false if it is not valid then ask the user to enter again as long as it is not valid.By writing a function in Javascript.
For names just string,hyphen and whitespace and for email just string,htphen,underscore,# and dot is valid.
1-How can i get rid of "acceptable" and just make it as return true/false?
2-How can I modify the code to validate both the email and first,lastname
because when i write # for example in firstname it accepts.
function validateText(text, validChares = "abcdefghijklmnopqrstuvwxyz -") {
let acceptable;
for (let t of text) {
acceptable = false;
for (let vc of validChares) {
if (t === vc) {
acceptable = true;
break;
}
}
if (!acceptable)
return false;
}
return true;
}
let validChars = "";
for (let i = 65; i <= 90; i++)
validChars += String.fromCharCode(i);
for (let i = 97; i <= 122; i++)
validChars += String.fromCharCode(i);
validChars += " #_-.";
//return validChars += " -";
let firstName = prompt("Enter your firstname");
if (validateText(firstName, validChars))
alert(`${firstName} is acceptable`);
else
alert(`${firstName} is not acceptable`);
while (!validateText(firstName)) {
firstName = prompt("Enter valid First Name:");
}
/**/
let lastName = prompt("Enter your lastname");
if (validateText(lastName, validChars))
alert(`${lastName} is acceptable`);
else
alert(`${lastName} is not acceptable`);
while (!validateText(lastName)) {
lastName = prompt("Enter valid Last Name:");
}
/**/
let email = prompt("Enter your email");
if (validateText(email, validChars))
alert(`${email} is acceptable`);
else
alert(`${email} is not acceptable`);
while (!validateText(email)) {
email = prompt("Enter valid Email:");
}
alert(`Registration data:\nName: ${firstName}\nSurname: ${lastName}\nEmail: ${email}`)
You can instead use regex to test your name and email
for name,
const onValidName = (val) => {
// name can contain
// CAPITAL ALPHABETS
// small alphabets
// whitespace
// hyphen
const nameRegex = /^[a-zA-Z- ]*$/
return nameRegex.test(val)
}
//it will log true if name is valid
console.log(onValidName(somename)
for email validation, you can use
const onValidEmail = (val) => {
// cheks for email is valid or not
const emailRegex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return emailRegex.test(val)
}
//return true if email is valid
console.log(onValidEmail(some email))
you can keep asking user for a valid name/email by this way
let lastName = prompt("Enter your lastname");
if (onValidName(lastName))
alert(`${lastName} is acceptable`); //update UI or write in DB or do whatever you want
else{
alert(`${lastName} is not acceptable`); //or you can show error in UI
prompt("Enter your lastname"); //again ask for a valid name
}
rest all validations for [name, email, etc] can be done in the same way

validation login with data stored on localStorage

the code i made only reads the last index from localStorage for login validation, can someone help to login using all existing data?
$('#btnlogin').click(function(){
var usernamelogin = $('#usernamelogin').val()
var passwordlogin = $('#passwordlogin').val()
var data_user1 = JSON.parse(localStorage.getItem('data_user'))
for(var i in data_user1){
var entry = data_user1[i]
}
if(usernamelogin == entry.username && passwordlogin == entry.password){
alert("Log in successfull")
window.location.href = "curhat.jsp"
}else{
alert("wrong username or password")
}
//console.log(data_user1)
//console.log('username = ' + entry.username)
})

Javascript call back function not working as expected. Trying to make sure all code is complete before the finalization logic is executed

I am trying to have a summary section in my website that will take all the results from other functions and display the information. I created the following functions and call path to try and get this but it appears that the callback is still being called before the largest function finishes.
Office.onReady(info => {
if (info.host === Office.HostType.Outlook) {
document.getElementById("app-body").style.display = "flex";
mainprocessing(finalization);
}
});
function mainprocessing(callback){
console.log("main processing")
reviewEmailInfo();
attachmentCheck();
checkBodyforLinks();
checkmsgforriskywords();
callback();
}
function finalization(){
console.log("entering finalization");
document.getElementById("riskscore").innerHTML = "This email has a riskscore of " + riskScore;
}
I put console.logs into each function at the beginning and end and this is what is in the logs
main processing taskpane.js:43
entering review email taskpane.js:122
entering attachment check taskpane.js:137
leaving attachment check taskpane.js:174
entering check body taskpane.js:192
leaving check body taskpane.js:196
entering check risky words taskpane.js:210
entering leaving check risky taskpane.js:38
entering finalization VM72 taskpane.js:9931
leaving review email VM72 taskpane.js:9002
[WDS] Live Reloading enabled.client:52
[WDS] Live Reloading enabled.
leaving review email taskpane.js:106
function checkBodyforLinks(){
console.log("entering check body");
Office.context.mailbox.item.body.getAsync(
"html",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
var parser = new DOMParser();
var bodyHtml = parser.parseFromString(result.value, "text/html");
//need to add check to ignore mailto: links
var linkDomains = [], links = bodyHtml.links;
document.getElementById("linkCheck").innerHTML = "No links found within email body";
for (var i = 0; i < links.length; i++){
linkDomains.push(links[i].href);
}
if (linkDomains.length > 0){
document.getElementById("linkCheck").innerHTML = "There are " + links.length+1 +"links in the email body";
}
}
);
console.log("leaving check body");
}
console.log("entering review email");
Office.context.mailbox.item.getAllInternetHeadersAsync(
function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
var headers = asyncResult.value;
var ReplyTo = headers.replace(" ","").match(/Return-Path:(.*)/);
if (ReplyTo.length != null){
var cleanEmail = ReplyTo[1].substring(1,ReplyTo[1].length);
if(cleanEmail == Office.context.mailbox.item.sender.emailAddress){
document.getElementById("reply-match").innerHTML= "The from and reply email address match";
}else{
riskScore += 5;
document.getElementById("reply-match").innerHTML= "The from and reply email address DO NOT MATCH. The sender is:" + Office.context.mailbox.item.sender.emailAddress + " and the reply addres is: " + cleanEmail;
}
}
var ARCAuthResult = headers.replace(" ","").match(/ARC-Authentication-Results:(.*)/);
var dkimChk = false;
var spfChk = false;
if(ARCAuthResult != null){
if(ARCAuthResult[1].search("spf=pass")){
spfChk = true;
}
if(ARCAuthResult[1].search("dkim=pass")){
dkimChk = true;
}
}else{
var AuthResult = headers.replace(" ","").match(/Authentication-Results:(.*)/);
if(AuthResult.length != null){
if(AuthResult[1].search("spf=pass")){
spfChk = true;
}
if(AuthResult[1].search("dkim=pass")){
dkimChk = true;
}}}
if(spfChk == true & dkimChk==true){
document.getElementById("dkimspfchk").innerHTML = "Both DKIM and SPF are safe";
}else if(spfChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "DKIM check failed";
}else if(dkimChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "SPF check failed";
}else{
riskScore += 10;
document.getElementById("dkimspfchk").innerHTML = "SPF amd DKIM check failed";
}
//Check for domain match between sender and reciever
var domainIndex = Office.context.mailbox.item.sender.emailAddress.indexOf("#");
var senderDomain = Office.context.mailbox.item.sender.emailAddress.slice((domainIndex+1), Office.context.mailbox.item.sender.emailAddress.length);
var receiverAddress = headers.replace(" ","").match(/To:(.*)/);
if (receiverAddress.length != null){
domainIndex = receiverAddress[1].indexOf("#");
var recieverDomain = receiverAddress.slice((domainIndex+1),receiverAddress.length-1);
if(senderDomain == recieverDomain){
document.getElementById("domainMatch").innerHTML = "This email comes from with your domain";
}else {
riskScore += 1;
document.getElementById("domainMatch").innerHTML = "This message comes from an external email address";
console.log("risk score after domain " + riskScore);
}
}
//var domainAge = domainWhois(senderDomain);
console.log("leaving review email");
return;
} else {
if (asyncResult.error.code == 9020) {
// GenericResponseError returned when there is no context.
// Treat as no context.
} else {
console.log("error");
}
}
}
);
return;
}

Comparing user sign up info in an array with user login input

I have two buttons: a sign up and a log in. I intend to collect the input form values from the sign up into an array (this works). I then want to compare the user input from the sign up with the user input from the login and notify the user that they are logged in. (I am yet to get started with localStorage and JSON. I want to get this done using arrays first).
I have tried using a for loop and if statements with logical operators (&&).
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
var custData = [];
custData.push(custName, custEmail, custPass);
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
for (var i = 0; i < custData.length; i++) {
if ((currentName === custData[0]) && currentEmail === custData[1] && currentPass === custData[2]) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
}
};
});
});
May be you could try only IF statement without the loop.
The following thing checks if there is such item in the array and if it IS, will do smth:
if (custData.indexOf(currentName) != -1
&& custData.indexOf(currentEmail) != -1
&& custData.indexOf(currentPass) != -1) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
I have been learning about localStorage. I decided to use it on this task. I collected the values that the user inputs when signing up, and 'saved' them on local Storage. I then collected the value the user inputs and 'retrieved' them via local Storage. Here is the code:
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
localStorage.setItem("name", "Raych") +
localStorage.setItem("email", "raych#gmail.com") +
localStorage.setItem("password", "hey"); ;
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
event.PreventDefault;
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
localStorage.getItem("name") +
localStorage.getItem("email") +
localStorage.getItem("password");
$("#userLogIn").text("You are logged in!");
});
});

Display array elements in html page as they are being entered

var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
for(i=0;i<contacts.length;i++){
document.getElementById("mydiv").innerHTML += contacts[i].fname+" "+contacts[i].lname;
}
}
I want to display only the new array elements. In the above code, every time a new element enters the array all elements are displayed. How can I avoid repetition? I think using the DOM is an option. I'm stuck trying to implement this.
You can do it like this, adding only the last element of array to innerHTML
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
Before you add all the elements you have to empty your div.
document.getElementById("mydiv").innerHTML = ''
Here is a working snippet of what you asked. you just have to take the last pushed object from the array and display the names.
Also your var fname, lname, email, phone is not required, You can set the object properties on the fly.
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
// var fname, lname, email, phone; //also this is not required. you can set dynamic property names in a object.
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length-1]; //take the last pushed object from the array
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if(!document.getElementById(lastNameFirstChar + "_holder")){
document.getElementById("mydiv").innerHTML += "<div id='"+lastNameFirstChar+"_holder' class='holder'><span class='charValue'>"+lastNameFirstChar+"</span></br></div>";
}
document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
}
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
EDIT: Since you said you can use Jquery I have updated the solution with Jquery.
just change:
if(contacts.length!=0){
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
The if check is for the start when length of array is zero

Categories