Check for valid email before running remaining javascript - javascript

I have a textbox where the user is required to insert a valid email address.
When the user submits a valid email address a loading graphic appears while the data is posted back.
The code below works fine for showing the loading graphic but it does not check that the email address is valid first. Can anyone help out?
$('#btnEmail1Submit').live ("click", function() {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
});
I am thinking that I need to put an if statement around the function that is run on click - so something like:
$('#btnEmail1Submit').live ("click", function() {
if(emailvalid == true) {
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /></div>').appendTo(".emailEditContainer");
}
});
I am using asp.net email validation - it looks something like this:
<asp:RegularExpressionValidator Display="Dynamic" ValidationGroup="PrimarySubmit" ID="RegularExpressionValidator1" runat="server" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail1" ErrorMessage="Invalid email address - " />

You will need to use a regex to test the email address for validity:
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][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 pattern.test(emailAddress);
};
That came from this question, so see that thread for more info.
You need to call that function with the email address provided by the user, so I'm assuming something like:
var email = $("#emailInput").val();
if(isValidEmailAddress(email)) {
//Do stuff
}

You should check the email validity using a regexp
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,}))$/
$('#btnEmail1Submit').live ("click", function() {
if(!email.match(re)) {
alert('invalid email');
return false;
}
$('<div class="submitBg"></div>').appendTo(".emailEditContainer");
$('<div class="submitLoadingCont"><img class="submitLoading" src="images/mypreferences/loading.gif" width="50" height="50" /> </div>').appendTo(".emailEditContainer");
});
The regexp comes from Validate email address in JavaScript?

Email validation has been discussed many, many times on SO, and elsewhere. In short it's hard (impossible) to do perfectly and is a trade off between maximising coverage of valid formats and minimising false positives. In fact all i do to validate email addresses is a basic sanity check. In pseudocode:
if (address.contains("#")) {
.. // then ok
}
Anything else is basically futile. Even if you spend ages constructing some insanely complex regex to comply with RFC822 to get most valid addresses (there are real addresses that don't comply with the RFC) - how do you know this inbox actually exists?

you can check this
function myClick() {
Page_ClientValidate();
if (Page_IsValid) {
return true;
}
else {
return false;
}
}
if you are using regularexpression validator then this can be used....

If you need to execute the aps validator to validate the email address, which seems to be pertinant to your question, then you need to call the generated javascript that does this before you make the call - so call:
if(Page_ClientValidate)
do your other stuff
However, this will run all of the page validation, not just the email.
If you need to only run the one validation call for this, you can look at the generted javascript on your page, and find where it does the call for your email validation, and call that. However, I would not recommend that, as it may change when the page is regenerated.
See CodeProject

Related

Bots are bypasing my script for blocking emails

I currently have a script for blocking non-business email addresses on my website form (Marketo) yet bots are still finding a way to bypass it. Today I got another "gmail" and "hotmail.fr" submission. Whenever I test my form it works but the bots are finding a way to bypass the script. I have also tried the honeypot method but it has not worked. They are also submitting with two-letter names, the past month has been really bad and I am desperate for help, I am not very good in JS so any help would be very much appreciated.
This is my script:
(function (){
// Please include the email domains you would like to block in this list
var invalidDomains = ["#gmail.","#yahoo.","#hotmail.","#live.","#aol.","#outlook.","#icloud.","#zoho.","#hubspot.","#gmx.","#yandex.","#mail.","#email.","#tutanota.","#trashmail.","#lycos.","#tutanota.","#protonmail."];
MktoForms2.whenReady(function (form){
form.onValidate(function(){
var email = form.vals().Email;
if(email){
if(!isEmailGood(email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage("Must be Business email.", emailElem);
}else{
form.submitable(true);
}
}
});
});
function isEmailGood(email) {
for(var i=0; i < invalidDomains.length; i++) {
var domain = invalidDomains[i];
if (email.indexOf(domain) != -1) {
return false;
}
}
return true;
}
})();
</script>```
Some bots when they run, they don't even execute the JavaScript on the page. They just take the fields, find the post request the form is submitting, and submit the fields to them with pre-defined values. Thus, ignoring your validation completely.
So now the solution would be checking the post request values on the backend. Some people use the fact that some bots are dumb, and they include a honeypot field in their fields. They mark it hidden with CSS on the frontend, but again, some bots are dumb, and they will fill it out regardless and send it in the post request. Now you can have your sever throw that out right away.

Email validation not working correctly using javascript

This is my email address validation code using JavaScript. The alert messages are correctly working but when I submit giving a valid email address it alerts 'Please provide a valid email address'. Please help me.
if(email=="")
{
alert("Enter emailid");
$("#email").focus();
return false;
}
else if(email!="")
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
//alert(email)
//alert(filter.test(email.value))
alert('Please provide a valid email address');
email.focus();
return false;
}
}
Not a direct answer to your question...but can you not use HTML5 email input for this purpose? Why write javascript code for email validation when the browser can handle it? Use something like this:
<input type="email" name="email">
There are many advantages to using this including on-screen keyboard to match it (adds # and .com options).
For different types of HTML5 input types, refer this: http://www.w3schools.com/html/html5_form_input_types.asp
Try this
function ValidateEmail(){
var email = $('#txtemail').val();
if(email=="")
{
alert("Enter emailid");
$("#txtemail").focus();
return false;
}
else if(email!="")
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email))
{
//alert(email)
//alert(filter.test(email.value))
alert('Please provide a valid email address');
$('#txtemail').focus();
return false;
}
}
}
Call the function ValidateEmail on the onclick event of your button. And also please note that you are doing something wrong with this line
if (!filter.test(email.value))
change this to be
if (!filter.test(email))
hope this helps.
Working DEMO
There is a small mistake in your code, which makes the alert to display.
Please look for this line in your code
if (!filter.test(email.value))
and replace with
if (!filter.test(email))
Variable Email holds the value of Email field of your form.
And another change would be, look for this line
email.focus();
and change this one to
$("#email").focus();

Javascript Regex to validate URL and Empty at the same time

I tried to write a regular expression to work with the position-absolute jQuery validation plugin to give error if the string is left empty OR its a invalid URL. It works well for the URl but doesn't give error if a empty string is there . Here's the regex
"regex": /^\S$|^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/,
Can somebody tell what's wrong in the regex?
EDIT:
I'm using this plugin for jQuery validation
Demo: Go to this URL and in the URL validtion section, remove HTTP and see the error messages
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
When I add required and URL validators together, it shoots 2 errors. But with only URL
validator, it doesn't say that its a Invalid URL. I just need 1 error for both Empty and
Invalid URL.
https://github.com/posabsolute/jQuery-Validation-Engine
Thanks
You can set the same generic error message for all errors using data-errormessage, so regardless of whether the field is empty or has an invalid value you will get the same message.
have you tried jQuery URL validation metohod ?
I wrote a small example how you could validate a email realy quick and easy. Without the hassle of using a plugin. If you use it just once you could just use
var emailaddressVal = 'nobody#example.cpom';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(emailaddressVal) && emailaddressVal.length > 0)
{
alert('Your email is valid.');
}
else
{
alert('The email is invalid')
}
However putting it in a function so you could use it multiple times. than put it in a function for example:
// Email check function
function checkEmail(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(email) && email.length > 0)
{
return true;
}
else
{
return false;
}
}
// Ussage
if(checkEmail('nobody#example.com'))
{
alert('SUCCESS!!');
}
else
{
alert('FAILED!!');
}

Running a script if form field validates as email

Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.

How to check form input in html form control

I have an html file which contains a form. There is lots of text typed input control need customer to input information. How do I check whether the customer's input is correct?
For example, I want to check if the username only contains digits, letters and '_'.
Please help me.
I'd appreciate if somebody can provide me a demo.
Thanks in advance!
Here’s one possible approach, for a simple task like the one given as example:
<script>
function check(elem) {
if(elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
return true;
} else {
alert(elem.getAttribute('data-msg'));
return false;
}
}
</script>
<input name=username pattern=[a-zA-z0-9_]{1,9} onblur=check(this)
data-msg="The user name may only contain letters A–Z, digits, and underlines and must be 1 to 9 characters.">
The idea here is to start with the HTML5 pattern attribute, specifying the allowed pattern of data as a regular expression. It already works on several modern browsers and does no harm when it doesn’t. Then you add an event attribute, which causes a JavaScript-driven check to be made, using the regular expression taken from the same attribute (with a prefix and postfix character added so that the check is made on the input item as a whole).
You may wish to display the error message in some less disruptive manner than via alert()
<input type="text" id="username" />
<span id="invalidMessage" style="display:none; color:Red"><img src="../../Images/error.gif" alt="OK" />invalidEmail。</span>
<script type="text/javascript">
$(document).ready(function() {
$('#username').blur(function() {
$('#invalidMessage').hide();
if ($('#username').val() != "") {
var email = /_*\w+(-?\w+)*#_*\w+(-?\w+)*(._*\w+(-?\w+)*)*.\w*/;
if (!email.test($('#username').val())) {
$('#invalidMessage').show();
}
}
});
});
</script>
There is a demo,hope can help you.
I would use something like this on the client side;
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}
//-->
</script>
Then, i would use more robust error checking on the server side to ensure you have valid data. If you can catch bad data at the client, its a plus, as it avoids the hit on the server, but the validation really belongs on the data on the server side, as its more secure and can be reused by other forms.

Categories