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;
Related
(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;
}
I need help with returning a boolean value from my validateItems() function. And my addPatrons() function (which calls the validateItems() function) must receive the boolean value returned by validateItems() and store it in a variable named "isValid". Then i need to Check the value of isValid if it is true, then use $('myform').submit(); but if it is false, then display "Patron Not Added!" in the endmessage.
this is what i have so far, its not finished because i am lost. its probably something simple but i am not getting it.
var validateItems = function () {
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if (firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
}
var lastName = $("lastname").value;
if (lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
}
var addpatron = function (validateItems) {
var isValid =
if () {
$("myform").submit();
}
else
if () {
$("endmessage").innerHTML = "Patron Not Added!"
}
}
var validateItems = function() {
var formValid = true
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if(firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
formValid = false
}
var lastName = $("lastname").value;
if(lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
formValid = false
}
return formValid
}
var addpatron = function(validateItems) {
var isValid = validateItems ()
if (isValid ){
$("myform").submit();
}
else if (){
$("endmessage").innerHTML = "Patron Not Added!"
}
}
You have to change your form element as below
<form onsubmit="return validateAndSubmit();" >...</form>
And use the validate function as below
validateAndSubmit(){
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(invalid) return false; // prevents the form from submitting
else return true; // submits the form
}
EDIT 1
if you don't have to submit the form literally, but only perform an operation on submit you can return false always.
validateAndSubmit(){
event.preventDefault();
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(!invalid){
addPatron(); // perform add operation only when form is valid
}
return false;
}
I have made the following changes.
returning false always.
If not invalid calling the addPatron() function
Added event.preventDefault() for additional event bubbling to stop.
So the validation for the form works, but I cannot get it to send to the php file. I'm assuming it has something to do with the return false/true and the end.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '')
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
if (email == '')
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
if (msg == '')
{
$('.msgerror').html('What can we help you with?').fadeIn(1000);
}
return false;
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
I think your last section of code should read like this:
if($.trim($('.nameerror').text()) == '')
{
// You can do stuff here first if everything is good.
return true;
}
else
{
// Or you can do stuff here for a failed submission.
return false;
}
You are exiting the function before the last if statement is checked.
You must use this code:
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '') {
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
return false;
}
if (email == '') {
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
return false;
}
if (msg == '') {
$('.msgerror').html('What can we help you with?').fadeIn(1000);
return false;
}
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
Instead of checking to see if a particular element has html in it... why don't you just set a flag? This makes everything a bit more simplistic.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
var flag = true;
//do this for each of your if statements
if(there is an error case) {
//do whatever you want to the DOM
flag = false;
}
return flag;
}
I have the function
function validateEmailp() {
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
}
return true;
}
HTML is
<input id="email" onblur="validateEmailp()"><div id="emailerrorz"></div>
After the user types in the input field a free e-mail he will get that error (we do not..)
But after he rectify the email to a non-free e-mail the error should clear up. How do i do that with javascript?
function validateEmailp() {
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) > -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
}
document.getElementById('emailerrorz').innerText = ''
return true;
}
Make an else case:
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
} else {
document.getElementById('emailerrorz').innerText = ""; // clear error
}