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;
}
Related
I'm working on recheck password while typing.Can anyone help me with the code that checks while typing password that shows a notification if it doesn't match entirely character by character while typing and that checks the length too when submit button is pressed in jquery or javascript
You can do this by several ways. This DEMO will solve your problem by using Jquery validation.
HTML
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="user[password]" id="user_password" required/><br>
<input name="user[password_confirmation]" required/>
</fieldset>
</form>
<button>Validate</button>
JQuery
jQuery('.validatedForm').validate({
rules: {
"user[password]": {
minlength: 3
},
"user[password_confirmation]": {
minlength: 3,
equalTo : "#user_password"
}
}
});
$('button').click(function () {
console.log($('.validatedForm').valid());
});
Original answer - https://stackoverflow.com/a/9717644/7643022
That answer gives you the solution to what you need. I have just modified the answer to what you desire.
html
<div class="td">
<input type="password" id="txtNewPassword" />
</div>
<div class="td">
<input type="password" id="txtConfirmPassword" onChange = "checkPasswordMatch();" />
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>
<div><input type="submit" id="submitbtn"/></div>
JQuery
var incorrectFlag = false;
function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
incorrectFlag = true;
else
incorrectFlag = false;
}
$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
$("#submitbtn").onclick(function(e){
e.preventDefault();
if (incorrectFlag){
alert("Password Incorrect");
} else {
$('form').submit();
}
});
});
The Actual password should be retrieved and stored somewhere, here I assumed it should be stored in the hidden input.
$(document.ready(
var actual_password = $("#hidden_input_password").val();
$( "#password_text_box" ).keyup(function(event) {
var input_Password = $(this).val();
if(input_Password.length > actual_password.length)
{
event.preventDefault();
event.stopPropogation();
return;
}
elseif(input_Password.length === actual_password.length){
if(input_Password===actual_password)
{
return;
}
else{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
else{
if(input_Password!===actual_password.slice(0,input_Password.length))
{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
});
);
I am working on a mvc 5 project .in contact us page I want user to send admin his / her emaiul address .so I want to validate email in javascript on that page .I wrote some code that does not work properly. I want you to help me plesae.
<script language="javascript">
function f1() {
var inputText = document.getElementById("email").value;
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.value.match(mailformat)) {
document.form1.text1.focus();
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
<form name="form" action="#" onSubmit="return f1()" method="POST">
<input type="email">
</form>
<script>
function f1(){
var email = document.forms["form"]["Email"].value;
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)#([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email)){
alert("You have entered an invalid email address!");
return false;
}
}
</script>
You don't want inputText.value only inputText like this
<input type="text" id="email" />
<input type="submit" onClick="f1()"/>
<script language="javascript">
function f1() {
console.log(document.getElementById("email").value);
var inputText = document.getElementById("email").value;
console.log(inputText)
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.match(mailformat)) { // <<<<<<< here
//document.form1.text1.focus();
alert("correct")
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
A basic HTML and JS working code for validating email with JS is given here for u-
function validateForm()
{
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
alert("Valid e-mail address");
return true;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Think, u have your answer :)
function validateEmail(email) {
var re = ([\w-+]+(?:\.[\w-+]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7});
return re.test(email);
}
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.
I added this code to my website:
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location = "member.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
}
</script>
<form action="">
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>
However, after i inserted the correct password & name, i only see the link became:
http://tool-box.weebly.com/test.html?loginname=jamie&loginpwd=198237645
What should i do? if i change window.location="member.html" to document.write("Password Correct!"), it worked correctly.
Please help.
You need to cancel the click action so the form does not submit
onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value); return false;"
I hope you realize this is NOT secure.
Couple of error in code
a) onclick of submit button doesn't return anything hence the form is submitted each time
b) use window.location.href
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location.href = "memeber.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
return false;
}
</script>
<form action="" >
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick = "return checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>
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.');
}
}