validation is not working on submit - javascript

I've created a HTML form, which takes some input values,like this:
<form name="form1" action="" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="button" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>
And I kept some validation in javascript to validate the shop name, phone number and email id.
<script type="text/javascript">
function validate()
{
var shop_name=document.form1.shop_name.value;
var email=document.form1.email.value;
var phn=document.form1.phn1.value;
var phnre=/^[0-9]*$/;
var emailre = /^(([^<>()\[\]\\.,;:\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(shop_name==='')
{
alert("Shop Name is required.");
return false;
}
if(phn==="")
{
alert("Mobile number is required.");
return false;
}
if(!phnre.test(phn))
{
alert("Invalid mobile number.");
return false;
}
if(!emailre.test(email))
{
alert("Invalid Email Id.");
return false;
}
return true;
}
</script>
but,it is not working on submitting the form,
Can anyone help me on this issue.

Firstly, your html has a few errors. The main reason this is working is because your button has type="button" this should be type="submit".
All in all your html should be:
<form name="form1" action="" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row">
<div class=" col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
</center>
</div>
</form>
Also, <center> is not supported in HTML5.
Hope this helps!

Change button to type submit.
function validate()
{
var shop_name=document.form1.shop_name.value;// better use like var shop_name=document.getElementById("shop_name").value
var email=document.form1.email.value;
var phn=document.form1.phn1.value;
var phnre=/^[0-9]*$/;
var emailre = /^(([^<>()\[\]\\.,;:\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(shop_name==='')
{
alert("Shop Name is required.");
return false;
}
if(phn==="")
{
alert("Mobile number is required.");
return false;
}
if(!phnre.test(phn))
{
alert("Invalid mobile number.");
return false;
}
if(!emailre.test(email))
{
alert("Invalid Email Id.");
return false;
}
return true;
}
<form name="form1" action="" method="POST" onSubmit="return validate();">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="submit" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>

You should read value in another way:
var shop_name=document.getElementById("shop_name").value;
var email=document.getElementById("email").value;
var phn=document.getElementById("phn1").value;
Additionally on 9 line you missed quoata after "row
button should be "submit":
<button type="submit" class="btn btn-lg btn-info">Submit</button>

Please use submit instead of button.
replace
<button type="button" class="btn btn-lg btn-info">Submit</button>
with
<input type="submit" class="btn btn-lg btn-info" value="submit">

just replace input type="button" to input type="submit"
<button type="submit" class="btn btn-lg btn-info">Submit</button>
try whole code it should be like this
<script type="text/javascript">
function validate(){
if(document.form1.shop_name.value == ""){
alert("Shop Name is required.");
return false;
}
var emailID=document.form1.email;
if ((emailID.value==null)||(emailID.value==""))
{
alert("Please Enter your Email ID")
emailID.focus()
return false;
}
var chk;
chk = echeck(emailID.value);
if(chk == "wrong")
{
emailID.value=""
emailID.focus()
return false;
}
function echeck(str)
{
var at="#"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(at,(lat+1))!=-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(dot,(lat+2))==-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(" ")!=-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
return "correct";
}
if(document.form1.phn1.value == ""){
alert("Please provide phone ");
return false;
}
return true;
}
</script>
<form name="form1" action="abc.php" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="submit" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>
Thank you...

I don't know how you reference this script to your HTML but i expect you are putting it in an unknown place regarding the HTML itself , here are Three working ways:-
Common thing in the three ways:
<button type="submit" class="btn btn-lg btn-info">
instead of
<button type="button" class="btn btn-lg btn-info">
as in the Fiddles
put the validate function definition in the window object:
window.validate = function(){.......};
Fiddle Here
Embed the script into the HTML itself:
<form></form>
<script>your validate function definition</script>
Fiddle Here
Put the script in an external file and reference it in the HTML file (Recommended)

Related

Not able to verify if input field is empty or not after clicking the sumbit button

I am basically checking to see if the input field(fullName) is empty or not. If it is empty, then I want to disable the submit button, and forcing the user to add text in the FullName field.
To achieve this scenario, I did the following(code below), but when testing, I am still able to click the submit button, even if the FullName field is empty. I am not sure, what I am doing wrong with the JavaScript code.
I am doing all of this inside an .htm file.
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
}
return true;
}
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
</fieldset>
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
} else {
return true;
}
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<fieldset>
<form name='form' id='form'>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button id="btn_sumbit" type="button" class="btn btn-namebtn" onclick='checkform(form)'>Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</form>
</fieldset>
</div>
</div>
Note:- You have not added form tag and onclick='checkform(form)' which created issue in your code.
Your JS is ok. There are some changes -
First, wrap the form content in a form with a name attribute of form.
Next, fire the checkform function on clicking the submit button.
Check the snippet below-
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
}
return true;
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<form name="form">
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name
<span class="required">*</span>
</label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button id="btn_sumbit" type="submit" class="btn btn-namebtn" onclick="checkform(document.form)">Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
Is this what you are attempting?
Onclick if value of input is empty then you will see alert and button will disable.
EDIT: Included comments in code.
//get FullName input by id
var FullName = document.getElementById("FullName");
//get button by id
var btn_submit = document.getElementById("btn_submit");
function checkform() {
//if FullName is empty then alert and disable button
if (FullName.value === "") {
alert("Please enter your name!");
btn_submit.disabled = true;
}
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button onclick="checkform();" id="btn_submit" type="submit" class="btn btn-namebtn">Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</div>
</div>

My form validation error message vanishes

I was trying to make a registration form using HTML, Bootstrap and JavaScript.
I am able to get the error message when a field is left empty, but the error message vanishes just after showing up. I don't know what am I doing wrong
function checkValidation() {
var firstName = document.getElementById('firstName').value;
if (firstName == "") {
console.log("enter");
document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
} else {
console.log("done");
}
}
<div class="container-fluid">
<div class="container">
<h2>Registration Form</h2>
<form class="form-horizontal" name="myForm">
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">
First Name
</label>
<div class="col-sm-10">
<input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
<div class="col-sm-12">
<p id="firstNameErrorMessage"></p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" onclick="checkValidation()">Submit</button>
</div>
</div>
</form>
</div>
</div>
You will need to use preventDefault in order to make it work as intended:
<div class="container-fluid">
<div class="container">
<h2>Registration Form</h2>
<form class="form-horizontal" name="myForm">
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">
First Name
</label>
<div class="col-sm-10">
<input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
<div class="col-sm-12">
<p id="firstNameErrorMessage"></p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" onclick="checkValidation(event)">Submit</button>
</div>
</div>
</form>
and
function checkValidation(e) {
e.preventDefault();
var firstName = document.getElementById('firstName').value;
if (firstName == "") {
console.log("enter");
document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
} else {
console.log("done");
}
}
Have a look here for some preventDefault questions:
How and when to use preventDefault()?
What's the difference between event.stopPropagation and event.preventDefault?

JavaScript Onclick is not working in tag

HTML:
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="new User().register()">REGISTER</div>
</div>
</form>
Js File
var User = function() {
var self = this;
self.register = function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/
var regEight = /^8[0-9].*$/
if($("#empId").val() =='')
{
alert(Language.InvalidEmployeeId);
return false;
}
if(mobile =='')
{
alert(Language.EmptyMobileNumber);
return false;
}
}
};
if i write a coding for click event like below its working when i use OnClick event function is not calling
$("#regBtn").click(function ()
{
new User().register();
})
how to make the onclick work.. thanks in advance
In onclick call a function that does new User().register().
Do not write literal expression, wrap that expression in function and call that function.
try with this code
$("#regBtn").click(function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/;
var regEight = /^8[0-9].*$/;
if ($("#empId").val() == '') {
// alert(Language.InvalidEmployeeId);
console.log("InvalidEmployeeId");
return false;
}
if (mobile == '') {
//alert(Language.EmptyMobileNumber);
console.log("Empty mobile number");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="javascript:if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn">REGISTER</div>
</div>
</form>
</div>
Do something like this...
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="registerUser()">REGISTER</div>
</div>
</form>
</div>
Java script
function registerUser(){
new User().register();
}
In this case the function registerUser() is re-usable as you commented above "Actually i want to make use of the onclick event so that function can be reused if i give a id i cant reuse that in another page".

How to send localstorage with form

I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>

Form Validation with jQuery - Weird Redirect

Alright, so I'm trying to do form validation with jQuery. Not sure why but when you click submit it redirects you to the page you're at already.
The forms action is blank and I included the javascript file in the header.
I will put the code below. Let me know if you see whats wrong. I want it to validate with jQuery then send you to a php file with those values in the method POST.
Register.js:
$(document).ready(function() {
$('button[name=regsubmit]').click(function(){
var fname = $('input[name=regfirstname');
var lname = $('input[name=reglastnaame');
var email = $('input[name=regemail');
var password = $('input[name=regpassword');
var repeatpassword = $('input[name=regrepeatpassword');
var username = $('input[name=regusername');
var atpos = email.indexOf("#");
var dotpos = email.indexOf(".");
if (fname==null || fname=="")
{
alert('First name must be filled out!');
return false;
}
if (lname==null || lname=="")
{
alert('Last name must be filled out!');
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert('Not a valid e-mail address!');
return false;
}
if (username==null || username=="")
{
alert("Username field must be filled out!");
return false;
}
if (password==null || password=="")
{
alert("Subject field must be filled out!");
return false;
}
if (repeatpassword==null || repeatpassword=="")
{
alert("Repeat password field must be filled out!");
return false;
}
if (password != repeatpassword)
{
alert("The passwords do not match!");
return false;
}
else
{
location.href="register.php";
}
});
});
Form:
<form name="register" method="POST">
<fieldset>
<div class="form-container row-fluid">
<div class="span6">
<div class="control-group">
<label class="control-label" for="regfirstname">First Name</label>
<div class="controls">
<input id="regfirstname" tabindex="1" name="regfirstname" type="text" placeholder="First Name" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regusername">Username</label>
<div class="controls">
<input id="regusername" tabindex="3" name="regusername" type="text" placeholder="Username" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regpassword">Password</label>
<div class="controls">
<input id="regpassword" tabindex="5" name="regpassword" type="password" placeholder="Password" class="input-large">
</div>
</div>
<div class="controls">
<button id="regsubmit" tabindex="7" name="regsubmit" class="button background-asbestos">Submit</button>
</div>
</div><!-- .span6 -->
<div class="span6">
<div class="control-group">
<label class="control-label" for="reglastname">Lastname</label>
<div class="controls">
<input id="reglastname" tabindex="2" name="reglastname" type="text" placeholder="Lastname" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regemail">Email</label>
<div class="controls">
<input id="regemail" name="regemail" tabindex="4" type="text" placeholder="example#example.com" class="input-large"</td>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regrepeatpassword">Repeat Password</label>
<div class="controls">
<input id="regrepeatpassword" tabindex="6" name="regrepeatpassword" type="password" placeholder="Repeat Password" class="input-large" required>
</div>
</div>
<!-- .span6 -->
<!-- span6 -->
</div><!-- .row-fluid -->
</fieldset>
</form>
Alright your JS and HTML is a big mess of stuff, so I won't recreate it all, but basics:
Give your form an ID:
<form id="SomeForm" name="register" method="POST">
Then prevent default action, and submit if passes:
// reference the button by the ID you gave it
$('#regsubmit').click(function(e){
// stop original submission
e.preventDefault();
// all your checking stuff here, but if true, then:
document.getElementById('SomeForm').submit();
});
This ensures that you are referencing the button correctly, preventing submission correctly, and submitting only if valid.
prevent default action on submit
$('button[name=regsubmit]').click(function(e)
{
e.preventDefault();
//your code below
}

Categories

Resources