Contact form doesn't accept Greek characters - javascript

When someone put Greek characters in the NAME field on SEND the contact form returns with an error report.
So, how do I edit my validation form to accept Greek characters in both NAME & MESSAGE fields?
function validation() {
var contactname = document.forms["contactfrm"]["name"].value;
var name_exp = /^[A-Za-z\s]+$/;
if (contactname == '') {
swal("You forgot your name...", " ", "warning");
document.forms["contactfrm"]["name"].focus();
return false;
} else if (!contactname.match(name_exp)) {
swal("Invalid name...", " ", "error");
document.forms["contactfrm"]["name"].focus();
return false;
}
var email = document.forms["contactfrm"]["email"].value;
//var email_exp = /^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (email == '') {
swal("You forgot to enter your email...", " ", "warning");
document.forms["contactfrm"]["email"].focus();
return false;
} else if (!email.match(email_exp)) {
swal("Your email address is invalid...", " ", "error");
document.forms["contactfrm"]["email"].focus();
return false;
}
var message = document.forms["contactfrm"]["comments"].value;
if (message == '') {
swal("No empty messages, please...", "warning");
document.forms["contactfrm"]["comments"].focus();
return false;
}
return true;
}

You can achieve this by changing the name expression to:
name_exp=/^[A-ZA-zΑ-Ωα-ωίϊΐάέήόύϋΰώΆΈΉΌΏΎΫ\s]+$/;
and email expression to:
//var email_exp=/^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp=/^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

Related

Email validation and not letting the visitor to pass if the email is invalid

We have a Shopify store and i have a script which validates the email adress and writes out if the email address is not good, another script is checking if the form is filled out and if it's not - it's not letting the customer to pass the next stage based on ID selector.
I only need this email validator to do the same thing as the other script, write out an alert when the email address is not correct and don't let them pass to the next step.
Can someone help with this? How to do that?
Script which validates the email address:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' e-mail address is valid!');
$result.css('color', 'green');
} else {
$result.text(email + ' Lūdzu, ievadiet derīgu e-pastu lai pabeigt pirkumu');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
Script which checks wheter the form was filled out or not:
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
})
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
}
};
Appreciate the help, what i'm missing here?
Thank you!
Use the email validation inside on onClick event like this and set the var allAreFilled false is email validation failed
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
});
/* Here email valdation */
const email = $('#email').val();
if( !email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
)){
allAreFilled = false;
}
/* terms and condtions check */
if( !$('#CartTermsDrawer').is(':checked') ){
allAreFilled = false;
}
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
return;
}
};

How to check if astring is contained inside a variable in javascript for a login

I have this code for a Login page:
console.log("[js/login.js] started");
// function
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
console.log(
"[js/login.js] request to get info sent [ " +
username +
":" +
password +
" ]"
);
if (username == "dev" && password == "dev") {
// here i have only this credentials to log on... I would like to add like more account...
alert("Welcome Back!");
console.log(
"[js/login.js] user " +
username +
" logged in with password " +
password +
" ."
);
window.close();
window.open("success.html");
console.log("[js/login.js] request to change page sent");
return false;
} else {
// wrong credentials
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("loginButton").disabled = true;
alert("Wrong Password, Blocked.");
console.log(
"[js/login.js] HTML elements blocked by too many wrong attemps"
);
return false;
}
}
console.log("[js/login.js] function validate started");
but i would like to make a var for example:
var userlist = "username:pass, username1:pass1, ect..."
and then i don't know how to check if the credentials the the user puts is contained inside this variable userlist
because i am new to javascript :(
if userList is an object like this:
{
username0:pass0,
username1:pass1
}
you can simply do this:
const checkUser = (username,password)=> {
if(userList[username]) return userList[username]===password
return false
}
userlist.split(",").forEach((s)=>{
var uname=s.split(":")[0];
var pass=s.split(":")[1];
if(uname==USERNAME && pass==PASSWORD)
return true;
});

How do I stop Javascript form validate submitting before json response has returned?

I have an html form that is validated by Javascript, but since connecting to an external API the form submits before the API queries have returned
All of the alerts are triggering correctly, however the last line of code - if (rtn) {
$('#saleForm')[0].submit();
} -
is resolving before the api call data returns and therefore once I accept the alerts the form always submits (as rtn is always true).
I am using setTimeout to wait for the return in the two if() blocks, and have tried a do/whilst loop around submit but that didn't work.
Is there a method I can use to force the submit to wait until all the previous conditions have been checked, before if(rtn)?
$('#saleForm').off('submit').on('submit', function(e) {
e.stopPropagation();
e.preventDefault();
var rtn = true;
if (window.hasIntegration == 'no' && $('#eventDate').val() == '') {
alert('Please choose the event date and time.');
$('#eventDate').focus();
return false;
}
$('.itemValue').each(function() {
if ($(this).val() == '') {
alert('Please ensure all values are entered.');
$('#ticket-rows').focus();
rtn = false;
}
});
if (!$('#terms').is(':checked')) {
alert('Please accept the terms and conditions.');
return false;
}
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
});
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
}, 1000);
}
if (rtn) {
$('#saleForm')[0].submit();
}
});
Thanks everybody! I have brought the submit function inside the setTimeout function, and then brought that whole block inside the $.get api call as per #Gendarme. I've also added else after the if integration == 2, to make the submit work if no integration exists. New code below. Works a treat now.
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
if (rtn) {
$('#saleForm')[0].submit();
}
}, 1000);
});
} else {
if (rtn) {
$('#saleForm')[0].submit();
}
}
});

'$' and 'document' are not defined - JQuery Mobile

JSHint Problems. console and FBT are also not defined.
As a result my button in page-signup does not work.
................................................................................................................................................................
(function () {
var emailAddressIsValid = function (email) {
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,}))$/;
return re.test(email);
};
var passwordsMatch = function (password, passwordConfirm) {
return password === passwordConfirm;
};
var passwordIsComplex = function (password) {
// TODO: implement password complexity rules here. There should be similar rule on the server side.
return true;
};
$(document).delegate("#page-signup", "pagebeforecreate", function () {
var $signUpPage = $("#page-signup"),
$btnSubmit = $("#btn-submit", $signUpPage);
$btnSubmit.off("tap").on("tap", function () {
var $ctnErr = $("#ctn-err", $signUpPage),
$txtFirstName = $("#txt-first-name", $signUpPage),
$txtLastName = $("#txt-last-name", $signUpPage),
$txtEmailAddress = $("#txt-email-address", $signUpPage),
$txtPassword = $("#txt-password", $signUpPage),
$txtPasswordConfirm = $("#txt-password-confirm", $signUpPage);
var firstName = $txtFirstName.val().trim(),
lastName = $txtLastName.val().trim(),
emailAddress = $txtEmailAddress.val().trim(),
password = $txtPassword.val().trim(),
passwordConfirm = $txtPasswordConfirm.val().trim(),
invalidInput = false,
invisibleStyle = "bi-invisible",
invalidInputStyle = "bi-invalid-input";
// Reset styles.
$ctnErr.removeClass().addClass(invisibleStyle);
$txtFirstName.removeClass(invalidInputStyle);
$txtLastName.removeClass(invalidInputStyle);
$txtEmailAddress.removeClass(invalidInputStyle);
$txtPassword.removeClass(invalidInputStyle);
$txtPasswordConfirm.removeClass(invalidInputStyle);
// Flag each invalid field.
if (firstName.length === 0) {
$txtFirstName.addClass(invalidInputStyle);
invalidInput = true;
}
if (lastName.length === 0) {
$txtLastName.addClass(invalidInputStyle);
invalidInput = true;
}
if (emailAddress.length === 0) {
$txtEmailAddress.addClass(invalidInputStyle);
invalidInput = true;
}
if (password.length === 0) {
$txtPassword.addClass(invalidInputStyle);
invalidInput = true;
}
if (passwordConfirm.length === 0) {
$txtPasswordConfirm.addClass(invalidInputStyle);
invalidInput = true;
}
// Make sure that all the required fields have values.
if (invalidInput) {
$ctnErr.html("<p>Please enter all the required fields.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
return;
}
if (!emailAddressIsValid(emailAddress)) {
$ctnErr.html("<p>Please enter a valid email address.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
return;
}
if (!passwordsMatch(password, passwordConfirm)) {
$ctnErr.html("<p>Your passwords don't match.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
if (!passwordIsComplex(password)) {
// TODO: Use error message to explain password rules.
$ctnErr.html("<p>Your password is very easy to guess. Please try a more complex password.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
$.ajax({
type: 'POST',
url: FBT.Settings.signUpUrl,
data:"email=" + emailAddress + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password + "&passwordConfirm=" + passwordConfirm,
success: function (resp) {
console.log("success");
if (resp.success === true) {
$.mobile.navigate("signup-succeeded.html");
return;
}
if (resp.extras.msg) {
switch (resp.extras.msg) {
case FBT.ApiMessages.DB_ERROR:
case FBT.ApiMessages.COULD_NOT_CREATE_USER:
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
break;
case FBT.ApiMessages.EMAIL_ALREADY_EXISTS:
$ctnErr.html("<p>The email address that you provided is already registered.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
break;
}
}
},
error: function (e) {
console.log(e.message);
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
});
});
})();

Uncaught ReferenceError: slickcontactparse is not defined

I am using a ajax-driven contact form and receive the error "ReferenceError: slickcontactparse is not defined".
Am not sure how to declare the function. Please help!!
js
$(document).ready(function(){
$('#slickform').submit(
function slickcontactparse() {
// EMAIL VALIDATION FUNCTION
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
// EDIT THIS SECTION IF DIFFERENT FORM ELEMENTS
// Values
var successmessage = "Thank you for email, we will be in contact soon!";
var failedmessage = "There was a problem, please try again!";
var usersname = $('#name');
var usersemail = $('#email');
var usersphone = $('#phone');
var userssubject = $('#subject');
var userscomment = $('#comment');
var usershuman = $('#human');
var isvalid = 1;
var url = "slickform.php";
//Checking information is correct before sending data
//CHECKING EMAIL IS PRESENT AND IS VALID
if (usersemail.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var valid = emailReg.test(usersemail.val());
if(!valid) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING EMAIL IS PRESENT AND IS VALID
//CHECKING USERS NAME IS PRESENT
if (usersname.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Name!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING USERS PHONE NUMBER IS PRESENT AND IS ONLY NUMERIC
if (usersphone.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var EnteredValue = $.trim(usersphone.val());
var TestValue = EnteredValue.replace(" ", "");
if (isNaN(TestValue)) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING SUBJECT WAS SELECTED
if (userssubject.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Select A Subject!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING SUBJECT WAS SELECTED
//CHECKING THE USER IS HUMAN
if (usershuman.val() != 15) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Your Are You Human Math Is Incorrect!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
//CHECKING THE USER IS HUMAN
if (userscomment.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('You Forgot To Leave A Message!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
/*
*
* POSTING DATA USING AJAX AND
* THEN RETREIVING DATA FROM PHP SCRIPT
*
*/
$.post(url,{ usersname: usersname.val(), usersemail: usersemail.val(), usersphone: usersphone.val(), userssubject: userssubject.val(), userscomment: userscomment.val(), usershuman: usershuman.val(), isvalid: isvalid } , function(data) {
if(data == 'success'){
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".successcontainer").html(successmessage);
$(".successcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$("#name").val('');
$("#email").val('');
$("#phone").val('');
$("#subject").val('');
$("#comment").val('');
$("#human").val('');
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
} else {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html(failedmessage);
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
});
}
);
});
Here's the php:
if(isset($_REQUEST["isvalid"])){
$youremail = "test#test.com";
$usersname = $_POST["usersname"];
$usersemail = $_POST["usersemail"];
$usersphonenumber = $_POST["usersphone"];
$mailsubject = "Contact From Your Slickform";
$subject = $_POST["userssubject"];
$usersmessage = $_POST["userscomment"];
$message =
"$usersname has contacted you from your site.
$subject:
Their Message is as follows:
$usersmessage
...............................................
Contact details:
Phone Number: $usersphonenumber
Email Address: $usersemail";
$headers = 'From:' . $usersemail . "\r\n";
mail($youremail, $mailsubject, $message, $headers);
echo "success";
} else {
echo "failed";
}
Any help is appreciated. Thank you!
Either do this:
$('#slickform').submit(function() { // remove the callback fn name
or make a global function and use it like this:
slickcontactparse() {
// all your code
}
$(document).ready(function(){
$('#slickform').submit(slickcontactparse); // call it here as callback
});

Categories