This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
This is my first post and I have a small issue. I'm trying to validate an email address on a form, but with no luck. I found this snippet on the internet but it doesn't seem to be working. I'm using Javascript at the moment to validate it. I don't usually use JS, so any help would be appreciated.
<script type="text/javascript">
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.forms.emailform();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.forms.emailform();
return false;
}
}
<?php
$addemail .= '
<form method="post" action="cart2.php" name="emailform" onsubmit="return validateEmail">
';
$addemail .= '
E-mail Address: <input type="text" name="email" value="'.$row6['email'].'" size="19" /><input type="hidden" name="cartid" value="'.$cart.'" />';
if ( $emailerror != '' )
{
$addemail .= '<img src="images/email_error.png" width="16" height="16" hspace="4" alt="E-mail Error" />';
}
$addemail .= '
<input type="image" name="Add E-mail Address" alt="Add E-mail Address" src="images/addemail.gif" style="vertical-align:middle" />
</form>
';
if ( $row6['email'] == '' )
{
$emailpresent = 0;
}
else
{
$emailpresent = 1;
}
}
$addemail .= '
</td>
</tr>
';
}
?>
Look at this example of how it can be done in Javascript:
<html>
<head>
<script type="text/javascript">
<!--
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
return false;
}
}
window.onload = function() {
document.getElementById('email_form').onsubmit = validateEmail;
}
</script>
</head>
<body>
<form id="email_form">
<input type="text" id="email">
<input type="submit">
</form>
</body>
</html>
Edit:
If you are sure that the users of your web page are using HTML5 compatible browsers you can use the following neater example for the same purpose:
<!DOCTYPE html>
<html>
<body>
<form>
<input type="email" pattern="^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$">
<input type="submit">
</form>
</body>
</html>
onsubmit="return validateEmail()"
You must add parentheses after validateEmail in order to call it or it will assume you're trying to return a method.
Related
I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.
I want to check the email validity in Javascript and then show alert box if its invalid and if valid then show the div2. But its not working
Here is javascript:
function _(x){
return document.getElementById(x);
}
function Phase1()
{
myemail = _("email").value;
var reg = /^(([^<>()[\]\\.,;:\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 (reg.test(designeremail) == false)
{
alert('Invalid Email Address');
}
else
{
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
}
Here is my html:
<form id="myform" onsubmit="return false" >
<div id="phase1">
<label>Email</label><div><input type="text" id="email" name="email" required></div>
<div><button onclick="Phase1()" class="btn"><strong>Next</strong></button></div>
</div>
<div id="phase2">
<label>Name</label><div><input type="text" id="mname" name="myname" required></div>
<div><button onclick="Phase2()" class="btn"><strong>Submit</strong></button></div>
</div>
</form>
but even with wronng email it proceeds and shows the phase2
I think this is js and not php. Btw, it's because probably you're testing on the wrong variable:
if (reg.test(designeremail) == false)
you're testing designeremail, which is different from email from the form which probably you wanted test against to.
So I currently have a download link and an input field for an email address on my website.
In order to download the file you first need to put in your email.
I use a form to do this, with the email field being an input field and the download button being a submit button.
I like HTML5's form validation (the required fields, field types etc, it all looks very nice).
The problem is that if I use onClick in my submit button then none of the nice form validation works.
<form>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" class="btn" onclick="downloadWin()" value="Windows">
<input type="submit" class="btn" onclick="downloadOsx()" value="Osx">
</form>
<script>
function downloadWin(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadWin&email='+email;
}
}
}
function downloadOsx(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadOsx&email='+email;
}
}
}
</script>
This might not be the cleanest way to do it, so please if you think you know a better way tell me :)
Try this:
<form onsubmit="download(this.email.value,this.system.value)" id="form">
<input type="email" id="email" name="email" placeholder="Please enter email" required>
<input type="radio" name="system" value="Win" required >Windows
<input type="radio" name="system" value="Osx" >Osx
<input type="submit" class="btn" value="Download">
</form>
<script type="text/javascript">
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault();
});
function download(email_value,sys_value){
location.href='http://s/index.php?page=download'+sys_value+'&email='+email_value;
}
</script>
Result:
try this code
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 downloadWin() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadWin&email=' + email;
}
}
return false;
}
function downloadOsx() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
return false;
}
Below is the working code snippet (without using HTML5 validation). You can run and test it. I have used the jquery with jquery.validate plugin. You can uncomment the commented code to redirect user to the target url. Let us know if this what you are looking for or not. Feel free to comment if there is anything that you feel confusing.
$(document).ready(function(){
$(".btn-download").on("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($("#validateForm").valid()) {
var name = $(this).val();
var email = $("#email").val();
if (name === "Windows") {
//location.href = 'http://s/index.php?page=downloadWin&email=' + email;
console.log('http://s/index.php?page=downloadWin&email=' + email);
}
if (name === "Osx") {
console.log('http://s/index.php?page=downloadOsx&email=' + email);
//location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form method="post" action="" id="validateForm" novalidate>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" name="btnSubmit" class="btn btn-download" value="Windows">
<input type="submit" name="btnSubmit" class="btn btn-download" value="Osx">
</form>
Hi i was created a new chat box,everithing is working but i need to when i click enter to sumit a message(to go to function Kucaj() ).Can you help me with that?
I add some code for enter but didnt work.Thanks
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<form name="forma2" action="login.php" method="post">
<table>
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" />
<tr>
<td colspan="2"><input type="submit" name"submit" value"Login"/td>
</tr>
<tr>
<td colspan="2">Registruj se!</td>
</tr>
<?php
exit;
}
?>
<html>
<head>
<title>Maturski rad</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
function Klikni(){
if(forma1.msg.value == ''){
alert('Upisi poruku!');
return;
}
var msg = forma1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
forma1.msg.value='';
}
xmlhttp.open('GET','insert.php?&msg='+msg,true);
xmlhttp.send();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 2000);
});
</script>
</head>
<body>
<form name="forma1" action="#" id="forma1">
Username: <b><?php echo $_SESSION['username']; ?></b></br>
Poruka: <br />
<textarea name="msg" style="width:500px; height:100px"></textarea><br />
Posalji<br /><br />
Izloguj se<br /><br />
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
event.Klikni();
}}
</script>
<div id="chatlogs">
Molim sacekajte da se ocita!!!
</div>
</body>
</html>
You can just add onsubmit=return Klikni(); attribute to your form and return false; to Klikni function without using .keypress(). Form submitted on user pressing enter is a default behaviour.
function Klikni(e) {
alert("Enter pressed");
return false;
}
<form name="forma1" action="#" id="forma1" onsubmit="return Klikni();">
Put your cursor into the field and press Enter.<br>
<input type="text">
</form>
try like this source,
form.submit(function(e) {
e.preventDefault();
$(this).find('[type=submit]').click();
$("form").submit();
})
Try keydown instead of keypress as:
$("forma1").keydown(function(event) {
You may use like this.It should be like this Klikni(); not like event.Klikni();
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
Klikni(); //no need of event there..
}}
</script>
I'm new to the web programming can you please tell me what's wrong with following code?
<!doctype html>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate (form) {
// valriable declaration
var returnValue = true;
var username = form.txtUserName.value;
var password1 = form.txtPassword.value;
var password2 = form.txtPassword2.value;
// check for UserName length
if (username.length < 6) {
returnValue = false;
alert("Your username must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtUserName.focus();
};
// check for password length
if (password1.length < 6) {
returnValue = false;
alert("Your password must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
// check for match of password field
if (password1.value != password2.value) {
returnValue = false;
alert("Your password entries did not match.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
return returnValue;
}
</script>
</head>
<body>
<form method="post" name="frmRegister" action="register.html" onsubmit="return validate(this);">
<div><label for="txtUsername">UserName : </label>
<input type="text" name="txtUserName" id="txtUserName" size="12" />
</div>
<div><label for="txtPassword">Password : </label>
<input type="text" name="txtPassword" id="txtPassword" size="12" />
</div>
<div>
<label for="txtPassword2">Confirm your password : </label>
<input type="text" name="txtPassword2" id="txtPassword2" size="12" />
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
</body>
</html>
first of all stop using return from event handler.
convert your code to
<form ... onsubmit="validate(event,this)">
change your function to validate(event,form);
wherever you feel form should not be submitted..
write :
event.preventDefault()
instead of return false
Demonstration :
http://codepen.io/anon/pen/kGmeL