Preventing form submission when input field is empty - javascript

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.

Related

JS setCustomValidity not work at first time

I want to make a custom validity message to my form, and there are some problem.
The validity message will show after click two times.
and if I don't input correct word "text" first time, then it will not submit anymore.
what's the problem in my code.
JS:
function a(){
jQuery("#text")[0].setCustomValidity("");
if (jQuery("#text").val() == "text"){
return confirm('sure?');
}
jQuery("#text")[0].setCustomValidity("Incorrect");
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post" onsubmit="return a();">
<input type='text' id="text"/>
<input type="submit" value="submit"/>
</form>
Please try to check below solution:
$(document).on('click',"#submit_btn", function()
{
if($("#text").val() === "text")
return confirm('sure?');
else
$("#text")[0].setCustomValidity("Incorrect");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post">
<input type='text' id="text"/>
<input type="submit" value="submit" id="submit_btn"/>
</form>

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');
}
}

validation of form inputs in JavaScript

I want to validate a input fields of form in javascript. I have searched a lot on net and always got different ways to do it. It was so confusing. I want for every single input if it is left empty an alert should popup. Here is my code
<form method="post" action="form.html" id="FormContact" name="frm">
<p>Full Name: <br /><br /> <input type="text" name="FullName" size="50" id="Name"></p>
<span id="error"></span>
<p>Email:<br /><br /> <input type="email" name="Email" size="50" id="Mail"></p>
<p> Subject:<br /><br /> <input type="text" name="subject" size="50" id="Subject"></p>
Message:<br /><br />
<textarea rows="15" cols="75" name="Comment" id="text">
</textarea> <br /><br />
<input type="submit" value="Post Comment">
</form>
I got it done sometimes but that only worked for Full Name field.
Thanks and regards,
You can do something like this, to have an alert popup for each empty input.
$('form').on('submit', function(){
$('input').each(function(){
if($(this).val() === ""){
alert($(this).attr('name') + " is empty");
}
});
});
http://www.w3schools.com/js/js_form_validation.asp
if you're willing to use javascript, this would be pretty easy to implement.
use jquery validation plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script>
$("#FormContact").validate({
rules: {
FullName: {
required:true
}
},
messages:{
FullName:{
required:"Please Enter FullName."
}
}
});
</script>
USE submit method of jquery the use each loop to validate the controls
LIVE CODE
$('form#FormContact').submit(function(){
var i= 0;
$('input').each(function(i,j){
if($(this).val() == "" || $(this).val() == undefined){
alert('empty');
i++;
}else{
i=0;
}
})
if(i == 0){
return false;
}else{
return true;
}
})

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();" />

OnSubmit Javascript not overriding submit action

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!

Categories