The code below validating correctly with exception to the email address field. Do you have any suggestions as to how I can modify the code to get the email address field validation working? I want to ensure real email addresses are being entered and accepted.
$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();
var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var re = /^(([^<>()[]\.,;: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,}))$/igm;
var errorMsg = "";
if ($.trim(fname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}
if ($.trim(lname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}
if ($.trim(gender) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("genderError").innerHTML = "Please select your gender.";
}
if ($.trim(bmonth) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(bday) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(byear) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(email) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter your email address.";
}
if (email.val() === "" || !re.test(email.val()))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a vaild email address.";
}
if ($.trim(pass1.length) < 6)
{
errorMsg = errorMsg + "1";
document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}
if (errorMsg === "")
{
//signupService.execute({});
Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
Apperyio.navigateTo('Position1');
}
);
}
Update: I was able to resolve the issue. Thank you for your help.
Here is the updated code:
$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();
var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var dateString = (bmonth + "/" + bday + "/" + byear);
var errorMsg = "";
if ($.trim(fname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}
if ($.trim(lname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}
if ($.trim(gender) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("genderError").innerHTML = "Please select your gender.";
}
var date_regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
if (!(date_regex.test(dateString)))
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
if ($.trim(email).length === 0) {
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
// e.preventDefault();
}
if (validateEmail(email)) {
//alert('Email is valid');
}
else {
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
// e.preventDefault();
}
if ($.trim(pass1.length) < 6)
{
errorMsg = errorMsg + "1";
document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "" & $.trim(pass1) !== "")
{
errorMsg = errorMsg + "1";
document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}
if (errorMsg === "")
{
//signupService.execute({});
Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
Apperyio.navigateTo('Position1');
}
);
}
Related
I did my form validation first and it worked.However, after i include my other functions in my javascript file, it stops working. I try to check all the functions but i couldnt find where did i do wrong. Im still new to javascript so thank you in advance for those that took their time to fix my problem.
var gErrorMsg = "";
function validateForm() {
"use strict";
var isAllOK = false;
gErrorMsg = "";
var fnameOK = FName();
var lnameOK = LName();
var emailOK = Email();
var addOK = Address()
var cityOk = City();
var pnOK = PN();
if (fnameOK && lnameOK && emailOK && addOK && cityOk && pnOK) {
isAllOK = true;
}
else {
alert(gErrorMsg);
gErrorMsg = "";
isAllOK = false;
}
return isAllOK;
}
function FName() {
var owner = document.getElementById("name").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your first name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your first name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function LName() {
var owner = document.getElementById("Lname").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your last name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your last name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function Email() {
var email = document.getElementById("email");
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email.value)) {
result = true;
}
else { //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address **\n"
}
return result;
}
function Address() {
var add = document.getElementById("address").value;
var addOk = true;
if ((add.length == 0)) {
gErrorMsg = gErrorMsg + "Your address cannot blank**\n"
addOk = false;
}
return addOk;
}
function City() {
var city = document.getElementById("city").value;
var pattern = /^[a-zA-Z ]+$/
var cityOk = true;
if ((city.length == 0)) {
gErrorMsg = gErrorMsg + "Please state the city you are form**\n"
cityOk = false;
}
else {
if (!pattern.test(city)) {
gErrorMsg = gErrorMsg + "Your city name must only contain alpha characters**\n"
cityOk = false;
}
}
return cityOk;
}
function PN() {
var pn = document.getElementById("phone").value;
var pnOk = true;
var pattern = /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if ((pn.length == 0)) {
gErrorMsg = gErrorMsg + "Please state your contact number**\n"
pnOk = false;
}
else {
if (!pattern.test(pn)) {
gErrorMsg = gErrorMsg + "Your contact number should only has 10 numbers*\n"
pnOk = false;
}
}
return pnOk;
}
function storeitem(item_id) {
sessionStorage.setItem("item_id", item_id);
window.location.replace("enquiry.html");
}
function displayitem() {
document.getElementById("sbj").value = "RE: Enquiry on " + sessionStorage.getItem("item_id");
}
function validateForm() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
return result;
}
//Store individual product page into sessionStorage
function storeProduct(productName) {
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
options.forEach(array);
function array(value) {
if (value == productName) {
sessionStorage.productIndex = options.indexOf(value);
}
}
}
//Fill the subject field with the value of product
function storeSub() {
document.getElementById("type").selectedIndex = sessionStorage.productIndex;
var product = document.getElementById("type").value;
sessionStorage.subject = product;
document.getElementById("subject").value = sessionStorage.subject;
}
//Storing first optgroup into array
function productlist1() {
var select = document.getElementById("type");
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
//change the value of the session storage according to the new product selected by user
function change() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
document.getElementById("subject").value = sessionStorage.product;
}
//if validateForm returns returns false nothing will be sent to the server
function init() {
var regForm = document.getElementById("form");
//Lecture 7 - following 2 calls register inputs elements to respond to onblur and onclick events.
//registerInputsOnBlur();
//registerInputsOnClick();
regForm.onsubmit = validateForm;
displayitem()
}
window.onload = init;
(I would like to adress that English is not my first language)
I have this problem with javascript for a very long time and I don't know what to do.
This javascript is for a registration. Sometimes it gives access even though I haven't typed everything, or it doesn't give access even though I have typed everything correctly
If someone can help thanks already!
function validateform() {
var res = true;
res = userNameVal() && res;
res = passowrdVal() && res;
res = ConfirmPhone() && res;
res = emailConfirm() && res;
res = Name() && res;
res = lastName() && res;
res = city() && res;
return res;
}
function Name() {
var firstName = document.getElementById("firstName").value;
var msgBox = document.getElementById("NameMsg");
if (firstName.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (reg.test(firstName) && reg1.test(firstName) && reg2.test(firstName) && (English(firstName))) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function lastName() {
var LastName = document.getElementById("LastName").value;
var msgBox = document.getElementById("LastNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (Name.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
if (reg.test(LastName) || reg1.test(LastName) || reg2.test(LastName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function city() {
var CityName = document.getElementById("CityName").value;
var msgBox = document.getElementById("CityNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (CityName.length == 0) {
msgBox.innerHTML = "You must enter your City";
return false;
}
if (reg.test(CityName) || reg1.test(CityName) || reg2.test(CityName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function userNameVal() {
var userName = document.getElementById("userName").value;
var msgBox = document.getElementById("userNameMsg");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter a username";
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "Your username must start with a letter";
return false;
}
msgBox.innerHTML = "";
return true;
}
function passowrdVal() {
var pass = document.getElementById("password").value;
var msgBox = document.getElementById("passwordMsg");
var specialChar = /[#!#$%^&*()-+]/;
if (pass.length == 0) {
msgBox = "You must enter a password";
return false;
}
if (pass.length < 7) {
msgBox.innerHTML = "The password must contain at least 7 charactes"
return false;
}
if (!specialChar.test(pass)) {
msgBox.innerHTML = "password must contain one special letter ";
return false;
}
msgBox.innerHTML = "";
return true;
}
function ConfirmPhone() {
var phone = document.getElementById("phone").value;
var msgBox = document.getElementById("phoneMsg");
var reg = /^0{1}(2|3|4|6|8|9|5[0|[2-8]|73)-?[1-9]\d{6}$/;
if (!reg.test(phone)) {
msgBox.innerHTML = "Phone number is illegal";
return false;
}
msgBox.innerHTML = "";
return true;
}
function emailConfirm() {
var email = document.getElementById("email").value;
var msgBox = document.getElementById("emailMsg");
var reg = /^\w+/;
if (!reg.text(email)) {
msgBox.innerHTML = "Mail can hava only one following letter";
return false;
}
msgBox.innerHTML = "";
reg = /^\w+([\.-]?\w+)*#\w+/;
if (!reg.test(email)) {
msgBox.innerHTML = "Mail must have #";
return false;
}
reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!reg.test(email)) {
msgBox.innerHTML = "invalid email";
return false;
}
msgBox.innerHTML = "";
return true;
}
function isLetter(ch) {
if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))
return true;
return false;
}
function isDigit(ch) {
if (ch >= "0" && ch <= "9")
true;
false;
}
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
We need more information about exactly what happens in your success and failure cases. However I see potential issues here:
For me, this function does not work for two reasons:
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
First, the variable i is not declared, do you mean this:
let i = 0
Possibly, i is declared globally, and so you are inadvertently trashing another value? Generally using let is preferable to using var, you can have other unexpected effects on globals if you use var.
Second, I don't see how this is working. For me str[i].isLetter is not defined.
while (str[i].isLetter) {
Do you intend to use your isLetter() function
isLetter(str[i])
If that doesn't help you will need to explain in more detail what happens in your failure cases.
I'm trying to make this work.
JS validation:
function validation() {
var fname = document.getElementById('fname').value;
if (fname == '') {
document.getElementById('fn').innerHTML = 'Please enter first name.';
}
var lname = document.getElementById('lname').value;
if (lname == '') {
document.getElementById('ln').innerHTML = 'Please enter last name.';
}
var birth = document.getElementById('birthdate').value;
if (birth == '') {
document.getElementById('bday').innerHTML = 'Please enter birthdate.';
}
var gender = document.getElementById('gender').value;
if (gender == 'select') {
document.getElementById('gndr').innerHTML = 'Please choose your gender.';
}
var username = document.getElementById('username').value;
if (username == '') {
document.getElementById('usr').innerHTML = 'Please enter username.';
}
var email = document.getElementById('email').value;
if (email == '') {
}
var econf = document.getElementById('econf').value;
if (econf == '') {
document.getElementById('rt-eml').innerHTML = 'Please confirm your email.';
}
if (econf != email) {
document.getElementById('rt-eml').innerHTML = 'Email did not match.';
}
var password = document.getElementById('password').value;
if (password == '') {
document.getElementById('pass').innerHTML = 'Please enter password.';
}
var pconf = document.getElementById('pconf').value;
if (pconf == '') {
document.getElementById('rt-pass').innerHTML =
'Please confirm your password.';
}
if (pconf != password) {
document.getElementById('rt-pass').innerHTML =
'Password did not match. Try again. ';
}
}
I want my check function to check if validation is true then change the innerHTML of success to You have successfully created an account.
JS check function:
function check() {
if (validation === true) {
document.getElementById('success').innerHTML =
'Your account has been successfully created.';
}
}
I know it's kinda messed up and I admit I'm still new to this.
A common way to do it is to initialize a boolean to true, if any field is empty or not valid then you assign false to this boolean. You return its value at the end of the validation function.
function check() {
//no need to check === true here
if (validation()) {
document.getElementById('success').innerHTML =
'Your account has been successfully created.';
}
}
function validation() {
let isValid = true;
var fname = document.getElementById('fname').value;
if (fname == '') {
document.getElementById('fn').innerHTML = 'Please enter first name.';
isValid = false;
}
var lname = document.getElementById('lname').value;
if (lname == '') {
document.getElementById('ln').innerHTML = 'Please enter last name.';
isValid = false;
}
var birth = document.getElementById('birthdate').value;
if (birth == '') {
document.getElementById('bday').innerHTML = 'Please enter birthdate.';
isValid = false;
}
var gender = document.getElementById('gender').value;
if (gender == 'select') {
document.getElementById('gndr').innerHTML = 'Please choose your gender.';
isValid = false;
}
var username = document.getElementById('username').value;
if (username == '') {
document.getElementById('usr').innerHTML = 'Please enter username.';
isValid = false;
}
var email = document.getElementById('email').value;
if (email == '') {
isValid = false;
}
var econf = document.getElementById('econf').value;
if (econf == '') {
document.getElementById('rt-eml').innerHTML = 'Please confirm your email.';
isValid = false;
}
if (econf != email) {
document.getElementById('rt-eml').innerHTML = 'Email did not match.';
isValid = false;
}
var password = document.getElementById('password').value;
if (password == '') {
document.getElementById('pass').innerHTML = 'Please enter password.';
isValid = false;
}
var pconf = document.getElementById('pconf').value;
if (pconf == '') {
document.getElementById('rt-pass').innerHTML =
'Please confirm your password.';
isValid = false;
}
if (pconf != password) {
document.getElementById('rt-pass').innerHTML =
'Password did not match. Try again. ';
isValid = false;
}
return isValid;
}
var objLogin = [{
fname: "sastry",
book: "sastry"
}, {
fname: "laxman",
book: "laxman"
}, {
fname: "visali",
book: "visali"
}]
function storeData() {
var userName = document.getElementById("fname").Value;
var userPasswd = document.getElementById("book").Value;
for (i = 0; i < objLogin.length; i++) {
if (userName == objLogin[i].fname && userPasswd == objLogin[i].book) {
console.log(userName + "Is logged in!!");
return;
} else {
console.log("Incorrect username or password");
}
}
}
When accessing the value of an input field, you should use value (lower case "v").
var userName = document.getElementById("fname").value;
Also, it's great to cache your element references, like this:
const userNameInput = document.getElementById("fname");
const userPasswdInput = document.getElementById("book");
function storeData() {
const userName = userNameInput.value;
const userPasswd = userPasswdInput.value;
for (i = 0; i < objLogin.length; i++) {
if (userName === objLogin[i].fname && userPasswd === objLogin[i].book) {
console.log(userName + "Is logged in!!");
return;
} else {
console.log("Incorrect username or password");
}
}
}
I think there is some typo.
var userName = document.getElementById("fname").Value;
var userPasswd = document.getElementById("book").Value;
As far as I know, document.getElementById("something").value is right;
Oh, someone answer that, but it's my first time to use stack overflow,
how can I do?
Can someone please tell me how to add my below JavaScript (function validateEmail() to the JavaScript I already created (function validateForm()? I need to combine the 2 into one. What I did was create a JavaScript to create error messages, then my new one creates an error message if the Email field was typed incorrectly. The longer JavaScript is what needs the shorter one. Do I just add an else if, if than? I am new to JavaScript. Thank you for those that help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
NEW JAVASCRIPT
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}
Your final function should look like below:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
ret &= validateEmail();
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}
EDIT
If you can not (or dont want to) change validateForm function to include call to validateEmail then you can specify both functions in the form onsubmit
onsubmit="return validateForm() && validateEmail()"
Your form validation script simply needs to call your additional function as an additional test.
Try adding this to the end of your main function:
if(!validateEmail()) {
// error code
ret=false;
}
else {
// ok
}
return ret;