How do I trim any dots before #mail.com? I am doing jQuery email validation and need to get rid of all the dots from username.
$('document').ready(function(){
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'email_check' : 1,
'email' : email,
},
success: function(response){.....
Use .replace(/\./g, "") for the part before #
function removeDots(email){
var email_s = email.split("#");
return email_s[0].replace(/\./g, "")+"#"+email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
In your code's context
function removeDots(email) {
var email_s = email.split("#");
return email_s[0].replace(/\./g, "") + "#" + email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
$('document').ready(function() {
var email_state = false;
$('#email').on('keyup', function() {
var email = $('#email').val();
email = removeDots(email); // call function here to remove dots
if (email == '') {
email_state = false;
return;
}
// Rest of your code
});
// Rest of your code
});
Regex: \.(?![^#]+$)
One line code: email.replace(/\.(?![^#]+$)/gy, '')
function myFunction() {
console.clear()
var s = document.getElementById("input").value;
console.log(s.replace(/\.(?![^#]+$)/g, ''));
}
<form action="javascript:myFunction()">
<input id="input" type="text" value="bla.bla.bla.#mail.net.com"><br><br>
<input type="submit" value="Submit">
</form>
First get the username of email using String.prototype.split() then remove all the . using .replace() and /\./g. Below is an example:
var email = "abc.d.e#mail.com";
var splitted = email.split("#");
console.log(splitted[0].replace(/\./g,"") + "#" + splitted[1]);
For updated question:
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
var splitted = email.split("#");
email = splitted[0].replace(/\./g,"") + "#" + splitted[1];
}
}
Related
I am new to php and jQuery but I managed to create a contact form that I send to my email address using jQuery ajax and php.
I have a small problem. My contact form is only sent if the user fills in all the entries directly. If for example, he writes an invalid email, there is the validation (client side) that is displayed and if he writes a valid email, the contact form is not sent anymore.
I think it's because of my isValid variable. If I understand correctly, I have defined a ValidateInputs function with some validations. And when there is no error, IsValid is set to true. I guess when I send the data to php via ajax, I set the isValid to true but I am probably missing something
Hope I am clear
Any help?
My javascript code:
$(document).ready(function() {
$('#contactForm').on('submit', function(event) {
event.preventDefault();
validateInputs()
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
if(isValid) {
$.ajax({
url: url,
type: type,
data: data,
});
console.log('send')
} else{
console.log('not sent')
}
return false;
});
});
var isValid = true;
function validateInputs() {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var subjectValue = $('#subject').val();
var messageValue = $('#message').val();
const regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (nameValue == '' ) {
$('#error').html('This field is required');
isValid = false;
} else if(nameValue.length < 3) {
$('#error').html('Name needs to be at least 3 characters');
isValid = false;
}
else {
$('#error').html('');
//$('.inputbox').css('border', 'solid 1px green');
}
if (emailValue == '' ) {
$('#errorMail').html('This field is required');
isValid = false;
} else if (!$('#email').val().match(regex)) {
$('#errorMail').html('Please enter a valid email address');
isValid = false;
}
else {
$('#errorMail').html('');
}
if (subjectValue == '' ) {
$('#errorSubject').html('This field is required');
isValid = false;
}
else {
$('#errorSubject').html('');
}
if (messageValue == '' ) {
$('#errorMessage').html('This field is required');
isValid = false;
} else if (messageValue.length < 20) {
$('#errorMessage').html('Name needs to be at least 20 characters');
isValid = false;
}
else {
$('#errorMessage').html('');
}
return isValid
}
And this is my PHP code:
<?php
if(isset($_POST['submit'])){
$mailto = "contact#statsmap.ch"; //Send the email to this address
//All the inputs informations
$mailfrom = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = "NAME: " .$name. "\r\n\n". "Wrote the following Message:" ."\r\n". $_POST['message'];
$message = $_POST['message'];
$headers = "From: ". $mailfrom;
$sendMail = mail($mailto, $message, $headers); // Send mail to website owner
}
?>
I'm trying to set some global vars but a little stuck on how to then fire the custom function which does a AJAX request with the data, I collect email in one function and other events and also firstname and lastname but I'm now stuck.
I've not called fireCheckoutAC anywhere as this is what I'm stuck with. I'm new to jQuery and JS but think I've got as far as I can.
// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
function fireCheckoutAC(checkoutEmail, checkoutFirstName, checkoutLastName) {
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'email': checkoutEmail,
'firstname': checkoutFirstName,
'lastname': checkoutLastName
},
caching: true
});
}
// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
field = $(field);
var email = field.val();
var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
var emailInputId = field.attr('id');
if ($("." + emailInputId + "_error_message").length > 0) {
$("." + emailInputId + "_error_message").remove();
}
//console.log($(emailInputId+"_error_message"));
if (validEmail(email)) {
//alert('valid email');
checkoutEmail = email;
field.removeClass('cm-failed-field');
field.prev().removeClass('cm-failed-label');
field.next("span").remove();
} else {
field.addClass('cm-failed-field');
field.prev().addClass('cm-failed-label');
field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
}
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
if (field.value) {
checkIt(field);
}
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
checkoutFirstName = $(firstname_sel).val();
checkoutLastName = $(lastname_sel).val();
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
if (firstname_sel_pre.value || lastname_sel_pre.value) {
checkoutFirstName = $(firstname_sel_pre).val();
checkoutLastName = $(firstname_sel_pre).val();
}
}
});
Managed to work it out, here is the solution for anyone else wanting to know... just had to call the ajax function which handled the global vars
/* grab completed email when enetred into checkout and add to abandoned cart
for that session */
function validEmail(v) {
var r = 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);
return (v.match(r) == null) ? false : true;
}
// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
function fireCheckoutAC() {
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'email': checkoutEmail,
'firstname': checkoutFirstName,
'lastname': checkoutLastName
},
caching: true
});
}
// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
field = $(field);
var email = field.val();
var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
var emailInputId = field.attr('id');
if ($("." + emailInputId + "_error_message").length > 0) {
$("." + emailInputId + "_error_message").remove();
}
//console.log($(emailInputId+"_error_message"));
if (validEmail(email)) {
//alert('valid email');
checkoutEmail = email;
fireCheckoutAC();
field.removeClass('cm-failed-field');
field.prev().removeClass('cm-failed-label');
field.next("span").remove();
} else {
field.addClass('cm-failed-field');
field.prev().addClass('cm-failed-label');
field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
}
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
if (field.value) {
checkIt(field);
}
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
checkoutFirstName = $(firstname_sel).val();
checkoutLastName = $(lastname_sel).val();
fireCheckoutAC();
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
if (firstname_sel_pre.value || lastname_sel_pre.value) {
checkoutFirstName = $(firstname_sel_pre).val();
checkoutLastName = $(firstname_sel_pre).val();
fireCheckoutAC();
}
}
});
I'm using remodal for the contact form on my website.
I'd like the modal box to close-out automatically after 1 or 2 seconds once the form is successfully sent.
The line used to close the modal box on success is inst.close();
I've tried this inst.close().FadeOut(3000); but that didn't work.
Thanks for your help
Code of my contact form:
// Contact Form
$(document).ready(function() {
$("#contactfrm").submit(function(e) {
e.preventDefault();
var inst = $.remodal.lookup[$('[data-remodal-id=modal]').data('remodal')]; // this was added by me
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "sendmessage.php",
data: dataString,
success: function() {
$('button[name="submit"]').hide();
$('.error').hide()
$('.success').fadeIn(1000);
inst.close(); // this was added by me
}
});
} else {
$('.error').fadeIn(1000);
}
return false;
});
});
I think that you need to work with callback functions:
$('.success').fadeIn(1000, function() {
inst.fadeOut(1000, function() {
this.close();
});
});
I want to post some data to controller using ajax, when someone press enter a textbox. My code working fine on Chrome but not in firefox. I have tried several solution but it did not work for me.Here is my code:
<input type="text" id="txtbox_#cmt.StoryActivityId" onkeypress="Reply(this)"/>
and
<script>
function Reply(e){
var id;
id = e.id;
var keycode = (event.keyCode ? event.keyCode : event.which);
if (event.keyCode == '13') {
//var txt1 = "\"";
//var txt2 = txt1.concat(id);
//var txt3 = "\"";
//var ActivityId = txt2.concat(txt3);
var storyActivityId = id.replace("txtbox_", "");
var liId = '#' + "liPartial_" + storyActivityId;
var txtId='#'+id;
//event.stopPropagation();
$.ajax({
url: '#Url.Action("PostReply", "Feed")',
type: 'post',
cache: false,
async: true,
InsertionMode: 'InsertionMode.InsertAfter',
data: { id:e.id,status:$(txtId).val()},
success: function (data) {
$(liId).append("<br>" + data);
$(txtId).val('');
}
})
}
}
You need to pass the event to that function,
<input type="text" id="txtbox_#cmt.StoryActivityId" onkeypress="Reply(event)"/>
Script
function Reply(event) {
var id;
id = this.id;
var keycode = (event.keyCode ? event.keyCode : event.which);
alert(keycode);
if (event.keyCode == '13') {
//var txt1 = "\"";
//var txt2 = txt1.concat(id);
//var txt3 = "\"";
//var ActivityId = txt2.concat(txt3);
var storyActivityId = id.replace("txtbox_", "");
var liId = '#' + "liPartial_" + storyActivityId;
var txtId = '#' + id;
//event.stopPropagation();
$.ajax({
url: '#Url.Action("PostReply", "Feed")',
type: 'post',
cache: false,
async: true,
InsertionMode: 'InsertionMode.InsertAfter',
data: {
id: e.id,
status: $(txtId).val()
},
success: function (data) {
$(liId).append("<br>" + data);
$(txtId).val('');
}
})
}
}
Demo
Change this:
onkeypress="Reply(this)"
To this:
onkeypress="Reply(event, this)"
Pass event as a first arguement.
I am trying to use ajax on a registration page in order to show either succes or errors. I cannot figure out why i get "Uncaught SyntaxError: Unexpected token I " in the console. Here is the code:
$("#submit").click(function(){
var name = $('#name').val();
var surname = $('#surname').val();
var username= $('#userName').val();
var email = $('#email').val();
var country = $('#country option:selected').text();
var password1 = $('#password1').val();
var password2 = $('#password2').val();
$.ajax({
url: "ajax-api.php",
type:'post', data:{name:name, surname:surname, username:username, email:email, country:country, password1:password1, password2:password2, submit:'yes'}
}).done(function(response) {
var errors = JSON.parse(response);
if(errors != ''){
var outputString = '';
for(var key in errors){
outputString += errors[key]+'<br /><br />';
}
alertify.error(outputString);
}else{
alertify.succes('You have been registered!');
}
});
});
});
The console says the error is in line 20 (var errors = JSON.parse(response);)
EDIT: I only get the console error in the success case( alertify.succes('You have been registered!');)