I'm new here and I'm not an expert of coding, I'm still learning, so be patient please. :)
I created a simple form that is supposed to send an e-mail with a CV attachment. I found the code for this job and it works as intended (sends the mail with file correctly). I didn't use phpmailer or similar, it's just the simple php mail function.
I want a client side validation, javascript/jquery classic, and maybe a server side later. The point is that I can't prevent the form from being submitted to process the javascript validation. I guess it's because there is a file (I used the same form, without attachments, elsewhere and it works pretty well). I post the code so you can see what's wrong:
<form method="post" action="mail.php" id="uploadform" enctype="multipart/form-data">
<p>Name :</p>
<input name="name" id="name" type="text" />
<p>E-mail :</p>
<input name="email" id="email" type="text" />
<p>Tel :</p>
<input name="tel" id="tel" type="text" />
<p>Message :</p>
<textarea name="mex" id="mex" rows="7" cols="10"></textarea>
<p>File Upload :</p>
<input name="file" id="file" type="file">
<input type="submit" name="submit" id="submit" value="send" />
</form>
and this is the script:
<script type="text/javascript">
$(document).ready(function () {
$('#uploadform').submit(function (){
validateForm();
return false;
});
function validateForm(){
var name=document.forms["uploadform"]["name"].value;
if(name==null || name=="") {
$('#name').attr("placeholder","Who is writing?");
return false;
}
var email=document.forms["uploadform"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
$('#email').val("");
$('#email').attr("placeholder", "Insert a valid e-mail address!");
return false;
}
}
});
</script>
I still can't find why the script doesn't prevent the data from being submitted. It seems it ignores the javascript at all. I tried also with different methods, like onsubmit inline on the form tag, event.preventDefault(); and similar, but the behavior is the same. I'm getting crazy for this small issue. I'd be glad if someone could help/explain. Thanks!
You have wrapped your check inside the callback of the submit function.
You should do it like:
$(document).ready(function () {
$('#submit').click(function (event){
return validateForm();
});
function validateForm(){
var name=document.forms["uploadform"]["name"].value;
if(name==null || name=="") {
$('#name').attr("placeholder","Who is writing?");
return false;
}
var email=document.forms["uploadform"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
$('#email').val("");
$('#email').attr("placeholder", "Insert a valid e-mail address!");
return false;
}
return true;
}
});
Let me know if that works.
Related
I am trying to make a very simple login page for a website I created and I am having issues with the submit button. I got the submit button to work fine if I use a "button" type in HTML however the Enter key does not work then. I discovered if I use a "submit" type, the Enter button and the mouse click will work however... the button now goes over my IF statement, straight to my Else statement. Any help would be appreciated.
HTML form:
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd();" />
</form>
JS code:
function checkPswd() {
var confirmPassword = "08012020";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location = "index.html";
} else {
alert("Password is incorrect, Please try again.")
}
}
Again, thank you in advance...
The key is returning false after calling your function, so the page redirect is not triggered by the input submission:
function checkPswd() {
let confirmPassword = "08012020";
let password = document.getElementById("pswd").value;
if (password === confirmPassword) {
alert("CORRECT!");
} else{
alert("Password is incorrect, Please try again.")
}
}
<form>
<label for="pswd">ENTER PASSWORD</label>
<br>
<input class="box" type="password" id="pswd">
<br>
<input class="confirm" type="submit" value="SUBMIT" onclick="checkPswd(); return false;" />
</form>
I would like to add that performing client-side password checking is very insecure since the source code can easily be inspected, so if you are hoping to use this in a real website I would suggest you consider a different approach!
let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>
I have a script that I have been using for a few years and it works on everything I use it on. It seems to be broken all of a sudden on a new script I am using it on.
I need for it to check that First Name was filled out and that the email address entered is a Gmail email address only.
I am hoping that someone can look at the code and let me know if I am missing something, or show me a better way to do this.
Here is my code:
<form name="myForm" method="post" action="putform3.php" onsubmit="return validateForm()">
<div class='card-img-top' style="position: relative; width: 300px; padding: 5px; background-color: #989eae;"><center>
<b>Fill Out The Form Below</b><br />
<input class='card-img-top' name="fname" type="text" value="" style="width:280px; margin-bottom:5px; color:#000000;" placeholder="First Name" required /><br />
<input class='card-img-top' name="email" type="text" value="" style="width:280px; margin-bottom:5px; color:#000000;" placeholder="Gmail Email" required /><br />
<input type="hidden" name="affiliate" value="$affiliate" />
<input type="hidden" name="myip" value="$ip" />
<input type="hidden" name="lp" value="$lp" />
<input class="formbutton" type="submit" name="submit" value="$buttontext"><br />
<span style="font-size: 10px;">We keep your information private!</span>
</center></div>
</from>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["myForm"]["email"].value;
var f=document.forms["myForm"]["fname"].value;
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
var gmail = e.split("#");
var rgmail = gmail[1];
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=e.length)
{
alert("Not a valid e-mail address");
return false;
}
if (rgmail == "yahoo.com" || rgmail == "hotmail.com" || rgmail == "msn.com" || rgmail == "aol.com" || rgmail == "yandex.com")
{
alert("Must Be A Good gmail.com Email Address");
return false;
}
if (f==null || f=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The javascript is totally being ignored. It's not that it's not working but it's never being used. I am totally lost here as it works on all my other scripts. I even put an alert('worked'); in the script to be sure it was being used and it's not showing the alert.
As per the website link provided:
There were multiple js issues on website which causes js validation function to run properly are:
use https: instead of http for jquery file include url
inside script.js file window.getComputedStyle is undefined
remove additional lname value line inside validation function as
there is no such input in the form
In mi validation form I have two input fields in order to write email and confirm it.
Before the submit informations, two confirms are needed:
1-email must seems an email,
2-email one must match the email two.
I can handle these statements each one using two separate javascript functions but i fail when I try to check them all in the onsubmit event attribute. If I write a correct email adress, the form reach the action destination, even if the confirm email doesn't match.
Looking around the web doesn't help me.
Here u are the code (html/javascript):
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Email Validation</title>
<script type="text/javascript">
function isEmail(email, output) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById(email).value;
if (regex.test(email)) {
return true;
} else {
document.getElementById(output).innerHTML = 'wrong email';
return false;
}
}
function compareEmail(email, emailToCompare, output){
var email = document.getElementById(email).value;
var emailToCompare = document.getElementById(emailToCompare).value;
if(emailToCompare == email){
document.getElementById(output).innerHTML = 'ok!';
return true;
}else{
document.getElementById(output).innerHTML = 'emails dont match!';
return false;
}
}
function check(){
return isEmail() && compareEmail();
}
</script>
</head>
<body>
<form action="file.php" method="post" onSubmit="return check()">
<p>Email</p>
<input type="text" name="email" maxlength="50" id="email">
<div id="email_result">
</div>
<br/>
<p>Confirm email</p>
<input type="text" onpaste="return false;" autocomplete="off" name="email" maxlength="50" id="confirm_email" onKeyUp="return compareEmail('email', 'confirm_email', 'confirm_email_result')">
<div id="confirm_email_result">
</div>
<input type="submit" name="submit" value="Register" onclick="return isEmail('email', 'email_result');">
</form>
</body>
The double control doesn't work with the follow script too:
function check(){
if (isEmail() && compareEmail()){
return true;
}else{
return false;
}
}
Nothing changes if I use:
onSubmit="return check()"
or
onSubmit="check()"
in the form event attribute.
You are missing the parameters in the function calls:
function check(){
return isEmail('email', 'email_result') && compareEmail('email', 'confirm_email', 'confirm_email_result');
}
Side note: You have declared variables in the functions with the same name as the parameters. It still works at it is, but the variables are not actually created but will overwrite the parameter values, so the code is a bit confusing.
The javascript:
function validateForm()
{
var x=document.forms["newsletter"]["agree"].value;
if (newsletter.agree.checked != 1)
{
alert("Checkbox must be checked");
return false;
}
var y=document.forms["newsletter"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
And my HTML
<div id="signup">
<form id="newsletter" action="" method="get" onsubmit="return validateForm()">
<fieldset>
<p>Email: <input type="text" name="email" size="35"/>
Please send me the monthly newsletter
<input type="checkbox" checked="checked" name="agree" value=""/>
<br/>
<input type="submit" value="Signup"/></p>
</fieldset>
</form>
</div><!-- signup -->
When I click submit with invalid entries in Chrome, the alert messages show and the form doesn't submit. However, when I do the same in Firefox, the form submits without an alert message.
I've been working on this for 5 hours, I truly have no idea. Thanks for any help, it's greatly appreciated.
I think it might help you.
<div id="signup">
<form id="newsletter" action="" method="get" onsubmit="return validateForm()">
<fieldset>
<p>Email: <input type="text" name="email" id="email" size="35"/>
Please send me the monthly newsletter
<input type="checkbox" checked="checked" name="agree" id="agree" value=""/>
<br/>
<input type="submit" value="Signup"/></p>
</fieldset>
</form>
</div><!-- signup -->
function validateForm()
{
var agreeEl = document.getElementById("agree");
if (agreeEl.checked != 1)
{
alert("Checkbox must be checked");
return false;
}
var emailEl = document.getElementById("email");
var atpos = emailEl.value.indexOf("#");
var dotpos = emailEl.value.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= y.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
First, is there some reason you are using 'get' instead of 'post' to submit your form? Chrome complains to me when I tried to submit your form using 'get'.
I setup a simple fiddle to test your form at http://jsfiddle.net/jsWyw/. Everything works fine if I use JQuery to handle the form submit instead of your 'onSubmit'. So I looked into what was going on with onSubmit and came across this thread: http://productforums.google.com/forum/#!topic/chrome/Z3MD5Od3oQM.
Things to try:
Make sure to use post instead of get
Use 'onSubmit' instead of 'onsubmit'
Make sure your script is included using <script type="text/javascript" src="javascript.js"></script>
If that fails, I would suggest handling the submit event yourself in Javascript instead of using onSubmit which seems to be a bit flaky in Chrome.
Did you look at your error console? Your validateForm handler is assuming that window.newsletter is a form element (instead of using document.forms["newsletter"] in that first if()), which it's not in Firefox in standards mode. So that line throws, and if an onsubmit handler throws the form will just go ahead and submit. But of course the error console is reporting that the handler threw.....
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;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>