Email validator - javascript

Having troubles with my email validation code. I keep on getting the error that my function is not defined. i have made a javascript file for the java code and then i used the onchange in my html to trigger the function.
<input type="text" id="email" name="email" onchange="check();" />
function check() {
email = document.getElementById("email").value;
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value))
{
document.getElementById("email").style.border = "3px solid green";
return true;
}
else
{
document.getElementById("email").style.border = "3px solid red";
return false;
}
}

Put your javascript in <script> tags.
Also rename your variable name email since your textbox is using it already.
<input type="text" id="email" name="email" onchange="check();" />
<script type="text/javascript">
function check() {
var email_x = document.getElementById("email").value;
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
document.getElementById("email").style.border = "3px solid green";
return true;
} else {
document.getElementById("email").style.border = "3px solid red";
return false;
}
}
</script>

Email validation is not always as simple as your regular expression. Have you looked at:
Validate email address in JavaScript?
A better option would be to use Verimail.js. It's a simple script that takes care of it for you. With Verimail.js you could just do:
var email = "cool#fabeook.cmo";
var verimail = new Comfirm.AlphaMail.Verimail();
verimail.verify(email, function(status, message, suggestion){
if(status < 0){
// Incorrect syntax!
}else{
// Syntax looks great!
}
});
The above example will hit the line 'Incorrect syntax!' because of the invalid TLD 'cmo'. Besides this, it will also give a suggestion that you can return to your user, in this case, the suggestion variable will contain 'cool#facebook.com' since 'fabeook.cmo' looks a lot like 'facebook.com'.
Hope this helps!

Here is the code for html input field and button field
<input input type="text" name="txtEmailId" id="txtEmailId" />
<input type="submit" class="button" value="Suscribe" name="Suscribe"
onclick="javascript:ShowAlert()" />
Now add the below function to the header of your page
<script type="text/javascript">
function ShowAlert() {
var email = document.getElementById('txtEmailId');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
else {
alert("Thanks for your intrest in us, Now you
will be able to receive monthly updates from us.");
document.getElementById('txtEmailId').value = "";
}
}
</script>
Here you can find the article on this Email Validation in JavaScript

If you are specific about the domains , you may use this code for email validation so as to prevent anonymous email domains.
(^([a-zA-Z]{1,20}[-_.]{0,1}[a-zA-Z0-9]{1,20})(\#gmail\.com|\#yahoo\.com|\#hotmail\.com)$)
You may add additional domains too.

Related

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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 (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

Regular expression for email not working

I am putting validation on email field but it shows error of invalid even where the email is typed in correct format.
Screenshot
Code
<script type="text/javascript">
function formvalidate(){
var email=document.signup_form.email.value;
var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$");
if(email=="")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
</script>
Thanks
try this function
function validateEmail(elementValue) {
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
Please refer this fiddle : http://jsfiddle.net/gabrieleromanato/Ra85j/
1- Use this regular expressions instead
\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
2- Change this if (!check_email.test(email)) to
if (check_email.test(email))
Try this fuction
function isEmail(inputString) {
var regExpEmail = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
try {
return regExpEmail.test(inputString.value);
}
catch (e) {
return false;
}
}
Change var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$"); to
a function like this:
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);
}
You regex is not correct, there are many things that you've not considered, like your regex accepts only capital letters, to include both capital and small letters you should use :
[a-zA-Z0-9]
not this :
[A-Z0-9]
You can use this regex for validating email :
/^(([^<>()\[\]\\.,;:\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,}))$/
read this for details
Source and some tests
You can use this regex for email:
RegExp('\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b', 'i')
try this example : email validation using JQuery
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);
}
function validate() {
$("#emailvalidate").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#emailvalidate").text(email + " is valid");
$("#emailvalidate").css("color", "green");
} else {
$("#emailvalidate").text(email + " is not valid");
$("#emailvalidate").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='btn'>Validate</button>
</form>
<h2 id='emailvalidate'></h2>
Try this code -
function formvalidate()
{
var email = document.signup_form.email.value;
var check_email = RegExp("^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$", 'ig');
if(email == "")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
<form name="signup_form">
<input type="text" name="email" value="" />
<input type="button" name="validate" value="Validate" onclick="formvalidate()"/>
</form>
I am using below regex to validate email pattern. Regex is not 100% solution to validate an email, better use email verification. Regex can help to validate format or pattern only.
Jsfiddle: DEMO
Jsfiddle: Regex check and sample email DEMO
function validateEmail(elementValue) {
document.getElementById('error').innerHTML = elementValue + ', email is incorrect';
var emailPattern = /^[a-z0-9](?:[a-z0-9]+\.)*(?!.*(?:__|\\.\\.))[a-z0-9_]+#(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9](?!$)){0,61}[a-zA-Z0-9]?)|(?:(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])))$/;
if (emailPattern.test(elementValue)) {
document.getElementById('error').innerHTML = elementValue + ', email is correct';
}
return false;
}
#error {
color: red;
font-size: 2rem;
}
input[type='email'] {
padding: 5px;
width: 300px;
border-color: blue;
font-size: 16px;
}
<form name="signup_form">
<input type="email" value="" onblur="validateEmail(this.value)">
<br />
<lable id="error"></lable>
</form>
Change your regular expression to below
^[a-zA-Z0-9._-]+#[A-Za-z0-9.-]+\.[a-zA-Z0-9.-]+$
Hope this helps :)

javascript password match if not match show in innerHTML

hi you write that code that is helpful for me but i want to show message in innerHTML when password not match how to do this i am trying but not working for me.below is my code .please guide me. i am beginner learner.
if (pwd != cpwd) {
document.getElementById("pwd").innerHTML="password must be match";
document.getElementById("cpwd").innerHTML="password must be match";
document.getElementById("pwd").style.color="RED";
return false;
}
i want to know about how to exactly write in innerHTML
below your code
<input id="pass1" type="password" placeholder="Password" style="border-radius:7px; border:2px solid #dadada;" /> <br />
<input id="pass2" type="password" placeholder="Confirm Password" style="border-radius:7px; border:2px solid #dadada;"/> <br />
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
}
}
Sumbit
Thanks for advance
waiting for your appreciate answer.
You should use the event onBlur tied to the field "pass2" in order trigger the first code snippet attached to your question.
For example:
document.getElementById("pass2").onblur=function(){
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
document.getElementById("pass1").innerHTML="password must be match";
document.getElementById("pass2").innerHTML="password must be match";
document.getElementById("pass1").style.color="RED";
return false;
}
return true;
};
Another option is to tie it to the submit button.
Add a div to store your password validation response to the document like <div id='validate'></div> and then after you have checked for passwords match, you can display the appropriate result in the html of this div
document.getElementById('validate').innerHTML="passwords do not match!";

JavaScript/jQuery validation for text box

I have a texbox that is like this:
<input type="text" size="30" name="form[id]" id="form_id">
I need a JavaScript function that will validate:
No Spaces allowed.
Only numbers, letters, dashes(-) and underscores(_) allowed and no other special character allowed.
Shouldn't be empty
On Submit when the user's input is violating a validation. An alert message should be displayed.
With jQuery I'll do something like that :
$('#formId').submit(function(e) {
var validator = new RegExp(/^[\w_-]{1,}$/), //Min 1 char or more
text = $('input[name="form[id]"]').val();
if(validator.test(text))
$(this).submit();
else {
alert('Code not valid');
return false;
}
});
Regular Expressions Cheat Sheet
NB : jsfiddle is down atm, code hasn't been tested
Here is the javascript
<script type="text/javascript">
function NoSpecialChars(){
var element=document.getElementById('form_id');
var specialchars= "!##$%^&*()+=[]\\\';,./{}|\":<>?";
if(element.value.length==0){
alert('Enter some text');
return false;
}
for (var i = 0; i < element.value.length; i++) {
if (specialchars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Those are not allowed.");
return false;
}
}
return true;
}
</script>
You need to subscribe the onclientclick event of the textbox.
<input type="text" size="30" name="form[id]" id="form_id" onclientclick="return NoSpecialChars();">
Hope it helps
Use JQuery Validation Engine for Validating the Form..
Here is the Link for JQuery Validation

Validating e-mail address

I am trying to validate an e-mail address using javascript. The problem is the if statements aren't executing correctly. If I delete the 'else statement' the code runs correnctly and the page does not load with errors. If I include the 'else statement' the else statement never executes and the status bar says that the page loads with errors. I was wondering if anyone can find any errors that I am unable to pick up?
<h4>Example 4:</h4>
<div style="border:3px dashed #aaa; width:200px;">
<div id="text">e-mail: <input id="email" onblur="verifyEmail()"/></div>
<div id="verification" > </div>
</div>
<script type="text/javascript">
function verifyEmail(){
var email = document.getElementById("email").value;
var atPos=0;
var dotPos=0;
atPos = email.indexOf("#");
dotPos = email.lastIndexOf(".");
if(atPos<=3 || dotPos<atPos+2 || dotPos+2>=email.length){
document.getElementById("verification").innerHTML = "Invalid E-mail Address";
}else{
document.getElementById("verification").innerHTML = "Valid";
}
}
</script>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
Read more: http://www.marketingtechblog.com/javascript-regex-emailaddress/#ixzz1wqetPJQQ
try this
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);
}
Demo : Here is the demo
OR a more simpler way is
function validateEmail(email)
{
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
if you are using HTML5 try <input type="email"... please note. this one works if the input is in a form tag with a submit button and isn't handled by JS
<input type="email" placeholder="me#example.com">

Categories