validation tells that all my email addresses are invalid - javascript

I do not know why it is telling me always that is an invalid email address even when it is correct.Any ideas? Demo on JSfiddle
my form
<form id="FormViewForm" method="post" action="/NewsletterMailer/subscribe/4" accept-charset="utf-8">
<input type="hidden" name="_method" value="POST" />
<input type="hidden" name="data[Form][id]" value="4" id="FormId" />
<input type="hidden" name="data[Form][type]" value="1" id="FormType" />
<input type="email" name="data[Form][e-mail]" value="" id="subscribe-email" placeholder="Enter your email..." required>
<input type="submit" value="+" class="large" id="subscribe-submit">
</form>
my custom.js
$('#FormViewForm').submit(function() {
validateEmail($('input').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}

Simply a jQuery selector issue, you're missing a #.
validateEmail($('#subscribe-email').val());
Your function receives undefined as an e-mail and the regex fails.
You could also use pure JavaScript. (Note that document.getElementById does not require the #, which might have caused the confusion.)
validateEmail(document.getElementById('subscribe-email').value);

Please use right selector like
If you want to user id as selector
validateEmail($('#subscribe-email').val());
Or you can also use input tag as selector
validateEmail($('input[type=email]').val());
The id selector will be strong to all browser and also safe to use
Please try this code
$('#FormViewForm').submit(function() {
validateEmail($('#subscribe-email').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}

Related

Form onSubmit validation not working

I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>

JavaScript Email address validation

I am making an HTML form with fields validation using JavaScript. I am stuck on email validation. I searched internet and found something like this-
JS Code
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length) {
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML Code
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Please explain me this?
Check this i am using something like this i minified some of them
You must Enter Valid Email address something like this Example#example.com
$(document).ready(function() {
$('.insidedivinput').focusout(function() {
$('.insidedivinput').filter(function() {
var emil = $('.insidedivinput').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (emil.length == 0) {
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.SendEmail').attr('disabled', 'disabled');
} else if (!emailReg.test(emil)) {
$('.SendEmail').attr('disabled', 'disabled');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
} else {
// alert('Thank you for your valid email');
$('.fa-close').css('display', 'none');
$('.sendmailbuttontrigger').removeAttr('disabled');
$('.fa-check').css('display', 'inline');
}
})
});
});
.fa-check{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' class='insidedivinput'><i class='fa-check'>Validated</i><i class="fa-close">UnValidated</i>
<button class="sendmailbuttontrigger" disabled>
Send
</button>
If you just want to validate an email address, you can use the validation that's built into HTML:
<form onsubmit="return false;">
<input type="email" required="1">
<input type="submit">
</form>
(Leave out the onsubmit for your own form, of course. It's only in my example to keep you from leaving the page with the form.)
I also searched on the Internet and use this one and it's working.
// email validation
checkEmail = (inputvalue) => {
const pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (pattern.test(inputvalue)) return true;
return false;
}

Validation with JavaScript

There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_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,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.

JavaScript validation - document.getElementById not working in Bootstrap modal

I am using an onSubmit() function to validate form entries.
The form and validation function work OK,if the form is in a standalone php file or an html file.
But when the form is embedded in a Bootstrap modal the JS validation function throws an error message. [object HTMLInputElement]
I have tried changing document.getElementById('uemail') to document.getElementById('uemail').value as recommended in another answer,
but no value has apparently been passed to the function.
If I remove the onSubmit() attribute then the values are passed correctly to the action script on the server.
This must be common usage. What am I doing wrong?
This is an abbreviated section of my code:
<script>
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail');
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
</script>
<form id="regform" action="action.php" method="post" onSubmit="return formCheck()">
Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id ="ast">*</span><br>
<input type="submit" name="Submit" value="Register" />
</form>
EDIT: looks like you can't do document.getElementById, you can do this instead:
function formCheck(formEl) {
//...
var email = formEl.getElementsByTagName("input")[0].value;
// this will get the first input-element in your form
and
onsubmit="return formCheck(this)"
Mistake: The variable email you are testing is a HTMLElement, not a string:
Solution: set email to the value of the HTMLInputElement:
var email = document.getElementById('uemail').value;
also email.focus; is not doing anything, use email.focus();
Demo:
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail').value;
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
<form id="regform" action="action.php" method="post" onsubmit="alert(formCheck())">
Email:
<input type="text" name="uemail" id="uemail" size="50" value="" required><span id="ast">*</span>
<br>
<input type="submit" name="Submit" value="Register" />
</form>

Javascript Form validation not working on any fields

Below is form validation using JavaScript but it's not working.
function validate()
{
var n=document.frm.name.value();
if(!n.match(/^[a-zA-Z]+$/))
{
alert("Enter valid Name");
document.frm.name.value="";
document.frm.name.focus();
return false;
}
var b=document.frm.mob.value();
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
return false;
}
var y=document.frm.nn.value();
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
return false;
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
return false;
}
}
<body>
<form name="frm" action="#" method="post" onsubmit="return validate()">
Name :<input type="text" name="name"/>
Mobile No:<input type="text" name="mob" />
Not Null :<input type="text" name="nn"/>
Email Id:<input type="text" name="email"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
First off, don't name your fields with reserved words (like "name")
Second, value is a property, not a method, so,
var b=document.frm.mob.value;
(without the brackets)
Please,place return false outside the function.
var b=document.frm.mob.value;
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
}
var y=document.frm.nn.value;
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
}
return false;
}
Instead of calling the function validate() in form tag on event onsubmit, better use it in submit button
<input type="submit" name="submit" value="submit" onClick="return validate()" />
It will work better and outputs as required.

Categories