How can I use validation with form without page refresh? - javascript

I am using a jQuery for mobile number validation without page refresh on submit button but it is not working and when I click the submitbutton. But with page refresh it works.
Here is my code:
index.html
<html>
<head>
<title>Submit Form Without Refreshing Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/refreshform.css" />
<script src="js/fresh.js"></script>
</head>
<body>
<div id="mainform">
<!-- Required div starts here -->
<form id="form">
<label>First Name:</label>
<br/>
<input type="text" id="fname" placeholder="First Name"/><br/>
<br/>
<label>Last Name:</label>
<br/>
<input type="text" id="lname" placeholder="Last Name"/><br/>
<br/>
<label>MobliNo:</label>
<br/>
<input type="text" id="mobile" placeholder="Your MobNo"/><br/>
<br/>
<label>ConfirmMobliNo:</label>
<br/>
<input type="text" id="remobile" placeholder="Confirm MobNo"/><br/>
<br/>
<label>Email:</label>
<br/>
<input type="text" id="email" placeholder="Your Email"/><br/>
<br/>
<input type="button" id="submit" value="Submit" onclick = "return Validate()"/>
</form>
</div>
</body>
</html>
refresh.js
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
});
});
function Validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^\d{10}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : " + mobile);
return true;
}
alert("It is not valid mobile number.input 10 digits number!");
return false;
}
What should I do to achieve validation without page refresh?

$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
should be
$('#form').submit(function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
or *)
$('#form').on('submit', function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
By including event.preventDefault() in the event handler, you block the default action for the element that triggered the event. In this case, the default action is submitting the form, so without this change, the form will still be submitted in the normal way, after it is submitted through AJAX.
*) Side note: on is a bit more flexible for binding events. You can also specify a selector as the second parameter. This way, you can set an event handler in the document (or another containing element), which will automatically be called for events on any child element that matches the given selector. This is especially useful if you have dynamic pages where elements are added or removed, because you won't have to add the event handlers every time you add an element. In this particular case it won't matter much, but I thought I'd let you know. The syntax for that is:
$(document).on('submit', '#form', function(event){

Do it in a slight different way. Remove
onclick = "return Validate()"
from the button and put that inside the click function like this
$("#submit").click(function(){
var valid = Validate();
if(valid){
/// Then your rest of process here.
}
});
Hope that works.
This will just check whether the phone number has 10 digits
function Validate() {
var mobile = document.getElementById("mobile").value;
var remobile = document.getElementById("remobile").value;
if(isNaN(mobile) || isNaN(remobile)){
alert("Invalid. Mobile and re mobile should be numbers only.");
return false;
}
if(mobile.length != 10){
alert("Invalid number. It should be 10 digits only.");
return false;
}
if(remobile.length != 10){
alert("Invalid Re mobile number. It should be 10 digits only.");
return false;
}
if(mobile != remobile){
alert("Mobile and remobile does not match!");
return false;
}
alert("Valid Number.");
return true;
}

in you form use:
<form id="form" onsubmit="return Validate();">
and button just submit:
<input type="submit" id="submit" value="Submit" />
in your js validate code instead of return true
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
return false;
in this case you will submit form without page refresh

function Validate() {
var mob = /^[1-9]{1}[0-9]{9}$/;
if (mob.test($.trim($("#<%=mobile.ClientID %>").val())) == false) {
alert("Please enter valid mobile number.");
$("#<%=mobile.ClientID %>").focus();
return false;
}

Related

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

Javascript Validation Not Working On Click Function

I am trying to validate a form using java script on click function i.e during form submit and if condition removed the i am getting the alert message but the alert message should be shown in if condition i.e when the form is empty
$(document).ready(function(){
$('#submit').click(function(){
var name = $().val("#name");
var email = $().val("#email");
if(name == '' || email == ''){
alert("test");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<input id="name" type="text" placeholder="name">
<input id="email" type="email" placeholder="email">
<button id="submit" type="submit">submit</button>
</form>
In jQuery, input values are retrieved with $(element).val(). Your variables should look like this:
var name = $('#name').val();
var email = $('#email').val();
$(document).ready(function(){
$('#submit').click(function(){
var name = $("#name").val();
var email = $("#email").val();
if(name == '' || email == ''){
alert("test");
return false;
}
});
});
You are not selecting the input elements you want to get the values from.
Replace
var name = $().val("#name");
var email = $().val("#email");
with
var name = $("#name").val();
var email = $("#email").val();

Execute code when textboxes have data

I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});

How to stop HTML to insert data into database when wrong input taken

So I have my form here
<form name = "reservation" method = "post" action = "makereservation.php" autocomplete="off">
(my codes here)
<input type = "submit" value = "Submit" onclick="checkPhoneNumber(document.reservation.contact)">
</form>
And my Javascript function here to detect wrong length of phone number
function checkPhoneNumber(contact)
{
var phoneno = /^\d{10}$/;
if(contact.value.match(phoneno))
{
return true;
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
What I want to ask is that how do I stop from inserting into database when the input for phone number is wrong?
What I got now is that it detects wrong length of phone number but it still insert into database.
Try this
<form name = "reservation" method = "post" action = "makereservation.php" autocomplete="off"
onsubmit="return checkPhoneNumber(document.reservation.contact)">
<input type = "submit" value = "Submit" >

javascript form validation object

Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.

Categories