Check for Valid Email with jQuery - javascript

I am trying to use jQuery to see if a user has entered a valid email address into my text box.
Basically, I want the submit button to remain disabled by default, but on each keyup I want to see if the email address is valid, then I want to enable the button. If the user enters a valid email but then deletes parts so that it becomes invalid again (i.e. the # symbol) I want the submit button to become disabled again.
I have a partially working script here. My check or the # symbol works well, but I am having a hard time checking for .com, .co, .net, .org, .edu etc... For some reason, the button keeps enabling even though I have not entered a valid "ending" to the email.
For example "emailco#" is recognized as a valid email. Here is my script:
<script>
$(document).ready(function() {
$('#email').bind('keyup', function(e) {
var email = document.getElementById("email");
if (email.value.search("#") != -1) {
if (
(email.value.search(".com") != -1)||
(email.value.search(".co") != -1)||
(email.value.search(".org") != -1)||
(email.value.search(".net") != -1)||
(email.value.search(".gov") != -1)||
(email.value.search(".biz") != -1)||
(email.value.search(".me") != -1)||
(email.value.search(".edu") != -1)) {
document.getElementById("email_go").disabled = false;
}
else {
document.getElementById("email_go").disabled = true;
}
}
else {
document.getElementById("email_go").disabled = true;
}
});
});
</script>

Just use regex:
if (email.value.search("#") != -1) {
if (/(.+)#(.+)\.(com|edu|org|etc)$/.test(email.value))
}

var email = $('#email').val();
var pattern = ".+\\##.+\\..+";
var valid = email.match(pattern);
if (valid == null) {
alert("Not Valid");
return;
}
else{
alert("Valid");
return;
}

Try this. Of course, this is just a basic example and I'm sure that email addresses nowadays can end in more than just what's specified in the array below. But, still... you get the idea...
// Split the email to see if there's an "#" character
var split = email.split('#');
var split_count = split.length;
// If there is, then split the second string by a "."
if (split_count == 2) {
var domain = split[1].split('.');
var domain_count = domain.length;
if (domain_count == 2) {
// Store all of the accepted values for email endings
var endings = ['org', 'com', 'net', 'edu', 'info', 'biz', 'me'];
var result = $.inArray(domain[1], endings);
// If the final 3 chars of the string are in the array, then proceed
if (result > 0) {
}
}
}

I use this Regex Code to test email format using jQuery:
var email = $('.email').val();
if(email.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/))
{
alert('OK');
}

Related

JavaScript Multiple Entry Form Validation

I am trying to use Javascript to validate user input before page redirects.
Users can either Input Student ID, Name, or Gender, and based on their input, they will be redirected to a URL.
However, I don't seem to get the multiple entries correctly in my javascript and nothing happened when the submit button is clicked.
I have tried different solutions which I found here.
see my JavaScript code below;
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("studentid").value;
if ( studentid == "12345" || studentid == "Daniel" || studentid == "Boy"){
alert ("Correct Input");
window.location = "https://www.google.com";
// Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I have tried to use the solutions below;
if ( studentid == "#12345, #Daniel, #Boy"));{
alert ("correct input");
window.location = "https://www.google.com";
// Redirecting to other page.
if ( studentid == '12345', 'Daniel', 'Boy'){
alert ("correct input");
window.location = "https://www.amazon.com";
// Redirecting to other page.
After so many attempts, I finally got it right!
var attempt = 3;
function check(form)
{
if(form.studentid.value == "12345" || form.studentid.value == "DANIEL" || form.studentid.value == "BOY")
{
window.location.replace('https://www.google.com')
return false;
}
else
{
attempt --;// Decrementing by one.
alert("ATTENTION!\nInvalid student ID!\nNot associated with any student!\nYou have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("studentid").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}

Show Validation in Signature field when field value is false?

I have to try to show validation when my signature field is blank. i am use alert message but it's not working like i am click on OK button and also show validation message but it's save form. So any one suggest me how to stop this continue show validation message if my field is blank and i have try to save.
My code is below :
on_save_sign: function(value_) {
var self = this;
this.$el.find('> img').remove();
var signature = self.$el.find(".signature").jSignature("getData",'image');
var is_empty = signature
? self.empty_sign[1] === signature[1]
: false;
if (! is_empty && typeof signature !== "undefined" && signature[1]) {
self.set('value',signature[1]);
}
else {
alert('Signature First');
self.do_warn(_t("Signature First"));
}
},
You can try following code.
on_save_sign: function(value_) {
var self = this;
this.$el.find('> img').remove();
var signature = self.$el.find(".signature").jSignature("getData",'image');
var is_empty = signature
? self.empty_sign[1] === signature[1]
: false;
if(is_empty){
self.do_warn("Please enter valid signature.")
}
if (! is_empty && typeof signature !== "undefined" && signature[1]) {
self.set('value',signature[1]);
}
},
Hope It will help you. If still not working try to use debug assets and reload the page. check your updated code is there by adding console in above conditions.
Have a good day !
on_save_sign: function(value_) {
this.$el.find('> img').remove();
var signature = this.$el.find(".signature").jSignature("getData", 'image');
var is_empty = signature
? this.empty_sign[1] === signature[1]
: false;
if (is_empty) {
this.do_warn("Please enter valid signature.")
}
else {
this.set('value', signature[1]);
}
}

jQuery / JavaScript test for email && checkbox validation

How do I test for form validation for both variables: emailAddr && items[].
items[] is a checkbox array.
Currently the code below won't submit the form at all.
jQuery(document).ready(function(){
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
var emailValue = email.value;
var testEmail = re.test(emailValue);
jQuery("#submitForm").on("click",function(){
if (jQuery("input[name*='items']").is(":checked"),
testEmail === true){
return true;
} else {
jQuery('#messages').append("You must choose at least 1 image<br>
Please enter a valid email");
return false;
}
});
});
Cleaning up the code a little to check for the value on submission may help but I do not know exactly how the html is formatted to see why else the form may not be submitting.
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
jQuery("#submitForm").on("click",function(e){
var emailValue = email.value;
var testEmail = re.test(emailValue);
if (jQuery("input[name*='items']").is(":checked") && testEmail === true){
return true;
} else {
e.preventDefault(); // prevents the form from submitting if invalid
jQuery('#messages').append("You must choose at least 1 image<br>Please enter a valid email");
return false;
}
});

validating custom domain for signup form using javascript?

I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.

how to check inserted regex pattern is valid or not

Hi guys I have to create a demo project, to check if inserted regex pattern is valid or not.
I have one text box.
With help of this text-box, I am entering the regex for date, email, time, etc.
But I don't know how can I do this type of validation check.
Help me out with this.
This is my fiddle: http://jsfiddle.net/ygfQ8/9/
It's not perfect, but just a view of how I am checking the pattern using jquery.
$('input').on('blur',function(){
var str = $('input').val();
var first = '(';
var last = ')';
var get_first = str.charAt( str.length1 );
var get_last = str.charAt( str.length -1 );
if(first==get_first && last==get_last)
{
alert('patter is valid');
}
else
{
alert('pattern is invalid');
}
});
and html textbox is <input type='text'>
This is php working demo:
<?php
//this variable containg any string .... doesnt matter wat ?
$subject = 'This is some text I am searching in'; //simple testing string variable
$pattern = '(fdsfdsfdsfdsfsd'; // user inputed string
if(#preg_match($pattern, $subject) === false)
echo "YOU have entered wrong regex pattern";
else
echo "Great work ";
?>
This could suit your needs:
function isPatternValid(pattern) {
try {
"".match(new RegExp(pattern));
return true;
} catch (err) {
return false;
}
}
Calling with:
$('#input').blur(function() {
alert(isPatternValid(this.value));
});

Categories

Resources