OnSubmit Javascript not overriding submit action - javascript

I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.

form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {

In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.

You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!

Related

check if input value not equal to integer then don't submit form

i have a simple php email form, but i am getting spam emails. I have added a check input, User have to fill the input. If input value equal to 12 then submit the form, otherwise don't submit the form with a popup error.(Please do the math.)
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
i am using php method below:
if(isset($_POST['not_robot']) !== 12 && isset($_POST['not_robot']) !== ''){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
when i submit form, error popup appear saying "Please do the math, if you are human", but after i close the popup, it also send email.
Any help appreaciated Thanks
P.S: if check method is possible using javascript or jquery it would be a great help.
You need to test on the client:
Plain JS
window.onload=function() {
document.querySelector("form").onsubmit=function(e) {
var val = this.elements["not_robot"].value;
return !isNaN(val) && parseInt(Number(val)) == val && !isNaN(parseInt(val, 10);
}
}
jQuery:
$(function() {
$("form").on("submit",function(e) {
var val = $("[name='not_robot'"].val();
if (isNaN(val) || !parseInt(Number(val)) == val || isNaN(parseInt(val, 10)) e.preventDefault();
}
}
Try to check when submitting the form. Go with below code or link-
JSFiddle
HTML Code-
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
JAVASCRIPT Code-
$('form').submit(function() {
if (parseInt($('input[name="not_robot"]').val()) == 12) {
return true;
}
else{
alert('You not enterd the correct value');
return false;
}
});
Don't try to prevent sending spam mail this way. My suggestion is to apply csrf protection and also google captcha. You can use this library for csrf protection. And for google captcha use this
If you want to validate through PHP..Below is the way
if(is_numeric($_POST['not_robot']) && !empty($_POST['not_robot'])){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
Ways :
Use PHP exit() function to exits the current script execution.we can use this function with (or without) an message.
Syntax : exit(message) OR exit()
We can also use return;
Here, the control will return to the script that invoked the running of that file.
Try this :
if(isset(($_POST['not_robot']) != '12') && (isset($_POST['not_robot']) !== '')){
/* alert here */
exit();
}else{
//email script here
}
HTML:
<form action="" method="post" name="form1">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" id="not_robot" required="required" />
</div>
<input type="button" value="submit" onClick="checkForm()">
</form>
JavaScipt:
function checkForm()
{
if(document.getElementById('not_robot').value == "12" && document.getElementById('not_robot').value != "")
{
alert('ok');
document.forms['form1'].submit();
}else{
alert('not ok');
}
}

JavaScript link error

I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
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(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>

Validating multiple form fields with JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded.
I'm working on this page: http://camp-tags.com/?main_page=contact
Thanks in advance for looking for me.
The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert.
Below is the code. (updated using the tips given here. No validation at all now.)
*update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong?
JS:
function validateForm(event){
var form1 = document.getElementById("form1"),
phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/;
var errors = [];
if (phone){
event.preventDefault();
errors.push("The Phone Number is required.");
return false;
} else if (tomatch.test(phone)){
return true;
} else {
event.preventDefault();
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
return false;
}
if (name === null || name === " "){
event.preventDefault();
errors.push("The Name is required.");
return false;
} else {
return true;
}
if (email === null || email === " "){
event.preventDefault();
errors.push("The email is required.");
return false;
} else if (emailMatch.test(email)){
return true;
} else {
event.preventDefault();
errors.push("The email must be formated as follows: name#domain.com.");
return false;
}
if (address === null || address === " "){
event.preventDefault();
errors.push("The Address is required.");
return false;
} else {
return true;
}
if(errors.length > 0){
for(var i=0;i<errors.length;i++){
alert(errors)
}
return false;
} else {
return true;
}
}
html:
Send Us An Email
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
<script type="text/javascript" src="./assets/validation.js">
I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function.
Executing event.preventDefault(); what do you think you have in event?
Properlly you should pass it when calling the function on submit and supply an argument in the function definition
onSubmit="validateForm(event);"
and function definition should be:
function validateForm(event) {
...
so you can do event.preventDefault()
...
}
You may have other problems too, but at least you will get the validation function executed and you;ll have event in it
COMPLETE EXAMPLE ADDED:
<script>
function validateForm(event) {
var phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/,
errors = [];
if (!phone){
errors.push("The Phone Number is required.");
} else if (!tomatch.test(phone)){
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
}
if (!name){
errors.push("The Name is required");
}
if (!email){
errors.push("The email is required.");
} else if (!emailMatch.test(email)){
errors.push("The email must be formated as follows: name#domain.com.");
}
if (!address){
errors.push("The Address is required.");
}
if (errors.length) {
event.preventDefault();
alert(errors.join("\n"));
}
}
</script>
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>

Simple JavaScript login form validation

Just a really simple login and redirect, but the script doesn't fire since I changed the button input type to 'submit' and the onClick event to onSubmit. All is does now is just add the username and password as a string to the url.
<form name="loginform">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login" onSubmit="validateForm();" />
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
window.location = "main.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this: <form name="loginform" onsubmit="validateForm()" method="post"> Here are some useful links:
JavaScript Form Validation
Form onsubmit Event
For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.
You can read more about the differences here.
UPDATE:
You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:
<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login"/>
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.
Option 1
<form name="loginform" onSubmit="return validateForm();">
Option 2
<input type="submit" value="Login" onClick="return validateForm();" />
<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;"> <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>
<form name="loginform" onsubmit="validateForm()">
instead of putting the onsubmit on the actual input button
Add a property to the form method="post".
Like this:
<form name="loginform" method="post">
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == null || username == "") {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
alert('Login successful');
}
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate();" />

Preventing form submission when input field is empty

When no value is provided to the roll input field an alert is produced by the empty() function but this empty value is still passed to retrive.php. So how can I stop this from happening and only pass the value to retrive.php when some input value is provided?
<html>
<head>
<title>STUDENT FORM</title>
<script type="text/javascript">
function empty()
{
var x;
x = document.getElementById("roll-input").value;
if (x == "")
{
alert("Enter a Valid Roll Number");
};
}
</script>
</head>
<body >
<h1 align="center">student details</h1>
<div id="input">
<form action='retrive.php' method='get'>
<fieldset>
<legend>Get Details</legend>
<dl>
<dt><label for="roll-input">Enter Roll Number</label></dt>
<dd><input type="text" name="roll" id="roll-input"><dd>
<input type="submit" value="submit" onClick="empty()" />
</dl>
</fieldset>
</form>
</div>
</body>
</html>
You need to return false to cancel the submit.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Enter a Valid Roll Number");
return false;
};
}
and
<input type="submit" value="submit" onClick="return empty()" />
jsFiddle example
How about using the required attribute?
<input id="Name" name="Name" class="form-control" placeholder="Enter name" type="text" required/>
Only works in html5 though.
The easiest way is to add attribute "required" into the input tag
<input type="text" name="name" required>
<form method="post" name="loginForm" id ="loginForm" action="login.php">
<input type="text" name="uid" id="uid" />
<input type="password" name="pass" id="pass" />
<input type="submit" class="button" value="Log In"/>
<script type="text/javascript">
$('#loginForm').submit(function()
{
if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") {
alert('Please enter Username and Password.');
return false;
}
});
</script>
</form>
i use with this I thinking it's maybe can help
$(function () {
$('form').submit(function () {
if ($('input').val() === "") {
alert('Please enter Username and Password.');
return false;
}
});
})
or work with class or ID like this
$('.inputClass')
$('#inputID')
If you want to save code you can simply do:
<input type="text" name="roll" id="roll-input">
<input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/>
I just say.

Categories