I have a field for users to write their e-mail address in. It is optional, so I need to first check if something was entered in the field, if nothing was entered then do nothing, but if something was entered than check if it is an e-mail.
Right now I'm at this point
var email = $("input#sc_email").val();
if (email == "") {
// If e-mail field is empty do nothing
} else {
// If something was entered
// [CODE HERE] Check if valid e-mail was entered, if not show error message
$("label#email_error").show(); //error message
$("input#sc_email").focus(); //focus on email field
return false;
}
I'm not even sure if that is right, but I think it is. Right now I need help with gaps in code, I marked them as [CODE HERE]. Could anyone suggest a solution please.
You could use the jQuery validate plugin for this, but if you only want to check the validity of an email address in one field, that is a little bit of overkill.
Instead, the regular expression in the function below will make sure the format of the email address is correct, should a value have been entered.
var email = $("input#sc_email").val();
if (email !== "") { // If something was entered
if (!isValidEmailAddress(email)) {
$("label#email_error").show(); //error message
$("input#sc_email").focus(); //focus on email field
return false;
}
}
function isValidEmailAddress(emailAddress) {
var pattern = 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][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
You could use regular expressions to validate the email address in JavaScript.
function validateEmail(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);
}
This will, however, only validate that it is a valid email address formatted string. flibble#flobble.com would be valid, even if no-one actually has that email address.
Have a look at this question.
I would recommend validation both at client side and at server side, you could simply use this code:
alert(/\S+#\S+\.\S+/.test('asdasd#asdasd#asdd.com'));
alert(/\S+#\S+\.\S+/.test('asdasd234#asdd.com'));
but importantly, use server side validation and methodology, like sending click-link-mail, to verify your client email address or mailing random number etc.
Related
Good day,
I've been working on this for class. I submitted the assignment and got a good grade - the professor didn't even lower my grade because I wasn't able to get this working, but I'm still frustrated because what I want this to do is to take a look at the Help Request form, alert me that it's checked, and to validate the email address. But the function seems to be unreachable.
I've made this fiddle here:
https://jsfiddle.net/b7j3ekts/
Stack overflow requires that I post code as well, but the fiddle is better I think:
/* This function never fired. I spent alot of time with it and I'm really frustrated and even though I posted my problem online and am going back and forth with
it, I kinda ran out of time to fix it. I was trying to do the part of the assignment where we looked to see if email was checked and then validated the email address. */
if (document.getElementById("contactemailH").checked === true) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\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 (document.forms["formHELP"]["FromAddress"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
}
The offending code starts at around line 123 of the js file.
Any advice appreciated. :)
-- Mark
if (document.getElementById("contactphoneH").checked === true ||document.getElementById("contactemailH").checked === true ) {
alert("Checked!");
/* Checks the email field to make sure that it's an email address in formHELP */
var emailaddy2 = /^(([^<>()\[\]\\.,;:\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 (document.forms["formHELP"]["FromAddressH"].value.match(emailaddy2)) {
}
else {
alert("Please input a valid email address.");
return false;
}
}
You just had misspelled tags.
You seem to need an event listener. The JavaScript loads once, does anything you've marked as immediate, and then it just sits there dormant. If you want a function to run you have to call it by name, or tell JavaScript to watch for an event.
In your case I'd tell JavaScript to wait for the event "blur", which is when an element was focused and then loses focus, so it's great for form fields.
document.getElementById('contactemailH').addEventListener('blur', function(event) {
validateEmail(event.target.value)
})
let validateEmail = function (emailaddy) {
// do your check here
}
Let me know if I'm off-base; I'm reading your fiddle on a mobile and jsfiddle is not mobile friendly at all.
I have a requirement what it meeans
if i entered email filed filled with #gmail.com, #hotmail.com,#outlook.com or #yahoo.com i need to show error like "Please Provide Your Company Email ID's And Don't Use Your Personal Mail ID's".
I want sloution in javascript language or sap ui5.
thanks in advance.
if (input4.toString() == "#gmail.com") {
this.byId("email").setValueState("Error");
this.byId("email").setValueStateText("Please enter company Emai Id");
return false;
} else {
this.byId("email").setValueState("None");
}
You can check if the e-mail address matches your pattern using a regular expression:
var email = input4.toString();
if (/#(gmail|hotmail|outlook|yahoo)\.com$/i.test(email)) {
// error
} else {
// success
}
The i behind the expression makes it case insensitive, so that upper-case domains will also be caught.
I'm creating an email form for our website. I built the form using HTML5 and CSS to take advantage of browsers' built-in validation (using this shim to avoid compatibility problems). Now I want to add a "confirm your email address" field, which shouldn't be marked valid unless it matches the "enter your email address" field.
I've written some JavaScript to compare the two fields. Is there a way for JavaScript to mark a field as valid/invalid for the browser's built-in validation? Or do I need to switch to a third-party validation plugin to get this feature?
Found the answer right after I posted the question. You call <element>.setCustomValidity() on the field, passing in an empty string to set the field as valid. If it's not valid, you instead pass in a string with the reason why.
Here's my code:
$('#emailConfirmation').on('keyup', function() {
if ($('#emailConfirmation').val() == $('#email').val()) {
$("#emailConfirmation")[0].setCustomValidity("");
} else {
$("#emailConfirmation")[0].setCustomValidity("Check that you've typed your email address the same way in both places.");
}
});
Here it is again without jQuery:
document.getElementById('emailConfirmation').onchange = function() {
if (document.getElementById("emailConfirmation").value == document.getElementById("email").value) {
document.getElementById("emailConfirmation").setCustomValidity("");
} else {
document.getElementById("emailConfirmation").setCustomValidity("Check that you've typed your email address the same way in both places.");
}
}
I'm using this ajax validation but it doesn't validate if the e-mail already exists in the database. It just goes through if you entered a valid e-mail address:
onSubmit="if(newsletterSubscriberFormDetail.validator.validate())
{
new Ajax.Updater({success:'newsletter-validate-detail'}, 'newsletter/subscriber/new',
{
asynchronous:true, evalScripts:false, onComplete:function(request, json)
{
Element.hide('newsletter-validate-detail');Element.show('pop-confirm');
},
onLoading:function(request, json){}, parameters:Form.serialize(this)
});
} return false;"
I have tried to modify the onsubmit function, but to no avail. I hope someone here can teach me how to make this validation work so that it will check if the entered e-mail already exists.
This is standard Magento behavior.
It doesn't check if the email already exists and always says "Thank you for your subscription".
You can check in Mage_Newsletter_SubscriberControllerin newAction that it'll only check for existing email if you're logged in and try to enter someone else's email address :
if ($ownerId !== null && $ownerId != $customerSession->getId()) {
Mage::throwException($this->__('This email address is already assigned to another user.'));
}
You'll probably need to rewrite this method to achieve that 'Email already exists' error.
Im using Joren Rapini's validation code to for my online form. Joren's Website
It allows you to check to see if an email address has been correctly entered, but I have 2 email addresses that I want to validate in the form.
Any idea how I would do this?
I've tried adding in email = $("#youremail"); as well as the one that's currently in the code which is email = $("#receiveremail"); but it only works for one.
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["youremail", "name", "receiveremail", "message"];
// If using an ID other than #email or #error then replace it here
email = $("#receiveremail");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field";
emailerror = "Not a vaild email";
});
He doesn't do a great job of explaining this, but it's fairly straightforward. You have to validate two separate email fields:
if (!/^S+#S+.S+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
var email2 = $("#youremail");
if (!/^S+#S+.S+$/.test(email2.val()) {
Of course it would be better to loop over the emails in a similar setup to how required is done.
Use var too.
You need to run the validation code for your other field
in document.ready
otheremail = $("#otheremail");
in form submit
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(otheremail .val())) {
otheremail .addClass("needsfilled");
otheremail .val(emailerror);
}
No offense to Joren Rapini but this code is hacky and shouldn't be used for other than the smallest purpose.