I have a bug that I could not figure out in my validation method. I have a function that validate the "code" table in my database to make sure the user can not input duplicate data. It is all working as expected and here is the code:
function validateCode() {
$('#code-error').html('')
if ($('#code').val() != '') {
$.ajax({
url: '${createLink(action:'checkCode')}',
type: 'GET',
data: {
'code': $('#code').val(),
},
// dataType:'json',
success: function (data) {
if (data == 'true') {
$('#code-error').html('Code already exist')
$(':input[type="submit"]').prop('disabled', true);
} else {
// $('#code-error').html('Code not exist')
$(':input[type="submit"]').prop('disabled', false);
}
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
}
But it is not stable.First the message and the button are disabled in the first couples of tried but if I continue to test it by re-enter the code that exist and the code that does not exist the button disabled however the error message is not showing under the input box.
Here is my html code :
<div class = "row" style = "margin-top:15px;">
<div class = "col-md-12">
<div class = "row">
<div class = "col-md-5 text-right" style = "font-weight: bold"><span class="placeholder">Code</span></div>
<div class = "col-md-7">
<div class="form-group">
<input style = "width: 50%"type="text" class="form-control" onkeyup="validateCode()" id="code" placeholder="Enter code" name="code">
<input type="hidden" name="current-code" id = "current-code">
<div class = "row">
<div id = "code-error" class = "col-md-12" style ="color:red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
And here is my controller function for validating the code:
def checkCode() {
def allow
String compareCode = params?.code
def customer = Customer.findByCode(compareCode)
if (customer == null) {
allow = false //not exist
} else if (customer != null) {
allow = true //exist
}
render allow
}
Related
I'm trying to create a checkbox list where a user is supposed to be able to choose one or more options, based on the choice: this is supposed to be inserted to a database table, where the id of the choice is inserted. (This is on a page where a user can "edit garage"), therefore the garageid is also supposed to be fetched and both the garageid and the choice id should be inserted to a cross table, that I have created as following:
[ID]
,[GarageID]
,[RequestProperty]
,[CreatedDate]
,[CreatedBy]
,[UpdatedDate]
,[UpdatedBy]
I also have a stored procedure for the insert:
ALTER PROCEDURE [dbo].[spGarageGetRequestTypes]
-- Add the parameters for the stored procedure here
#GarageID INT,
#RequestType INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO GarageCrossRequestType
(GarageID, RequestProperty)
VALUES (#GarageID, #RequestType)
END
And the "edit page" is working and functioning, it's where I get the garageId as well. It looks like following in view:
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Garage</label>
<input type="text" class="col-lg-10 form-control" name="GarageName" id="GarageName" placeholder="Name" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Contact person</label>
<input type="text" class="col-lg-10 form-control" name="ContactPerson" id="ContactPerson" placeholder="ContactPerson" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Email</label>
<input type="email" class="col-lg-10 form-control" name="Email" id="Email" placeholder="Email" required="" onblur="validateEmail(this.value);" /><p id="InvalidMeg" style="font-size: 25px; color: red">Invalid e-mail address</p>
</div>
</div>
<script type="text/javascript">
function editGarage(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var garageId = dataItem.GarageId;
countryId = dataItem.CountryId;
var email = dataItem.Email;
var contactperson = dataItem.ContactPerson;
if (garageId != 0) {
$("#EditGarageBtn").show();
$("#saveNewGarageBtn").hide();
$("#GarageName").val(name);
$("#Country").val(countryId);
$("#ContactPerson").val(contactperson);
$("#Email").val(email);
}
}
$("#EditGarageBtn").click(function () {
var customerNumber = customerNumberOfEditingGarage;
name = $("#GarageName").val();
countryId = $("#Country").val();
var garageId = $("#garageId").val();
var contactperson = $("#ContactPerson").val();
var email = $("#Email").val();
$("#EditGarageBtn").hide();
if (name.length > 0 && email.length > 0 && contactperson.length > 0) {
$.ajax({
url: '#Url.Action("EditGarage", "Garage")',
dataType: 'JSON',
data: {
name: name, countryId: countryId, garageId: garageId,
contactperson: contactperson, email: email
},
success: function (data) {
if (data == "Failure") {
toastr["error"]("Error editing Garage");
}
else {
toastr["success"]("Garage successfully updated");
customerNumberOfEditingGarage = null;
refreshGrid();
}
},
error: function () {
}
});
} else {
toastr["error"]("Error editing Garage");
}
});
</script>
Model:
public class GarageModel
{
public int GarageTypeId { get; set; }
public int CountryId { get; set; }
public string ContactPerson { get; set; }
public string Email { get; set; }
public int GarageId { get; set; }
// for the choices in the checkbox
public int ScheduledService { get; set; } = 1;
public int Tires { get; set; } = 2;
}
Method:
public bool EditGarage(GarageModel model)
{
var valid = false;
var cmd = new SqlCommand("spGarageEditGarage", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd.Parameters.AddWithValue("#CountryId", model.CountryId);
cmd.Parameters.AddWithValue("#Name", model.Name);
cmd.Parameters.AddWithValue("#ContactPerson", model.ContactPerson);
cmd.Parameters.AddWithValue("#Email", model.Email);
try
{
int result = cmd.ExecuteNonQuery();
if (result == 1)
valid = true;
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
Connection.Close();
}
// for the choices in the checkbox (not working!)
List<int> newlist = new List<int>();
newlist.Add(model.Tires);
newlist.Add(model.ScheduledService);
foreach (var item in newlist)
{
if (newlist != null)
{
var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd1.Parameters.AddWithValue("#RequestType", newlist.First());
int result = cmd1.ExecuteNonQuery();
if (result == 1)
valid = true;
}
}
return valid;
}
If you look at my comments in the model and the method, you can see what I've added for the "choices" function I'm trying to implement. Here's the html i created for the input type as well:
#foreach (var items in Model)
{
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Tires</label>
<input type="checkbox" class="checkbclass" name="#items.Tires" id="Tires" placeholder="Tires" required="" value="#items.Tires" />
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Scheduled Service</label>
<input type="checkbox" class="checkbclass" name="#items.ScheduledService" id="Scheduled" placeholder="Scheduled" required="" value="#items.ScheduledService" />
</div>
</div>
}
Now, to the problems:
1: I need some sort of method for making sure which or if a checkbox is checked, and this needs to be returned to the model or controller in some way. I only want to return it's numeric value, as seen in the model I want Tires to have the numeric value of 2 etcetera.
The datebase insert works (so at least that's something), but the table only accepts RequestProperty and GarageID, meaning that if a user chooses 2 of the checkboxes, I need to update the database twice, creating 2 rows, but with the same garageid.
I tried posting a question about this earlier, but it was poorly explained from my side, so I'm trying again, and hoping I included everything this time. I'm open to any help/solutions that can help me solve this.
First, You need to remove all GarageCrossRequestType that containe current GarageID as the checkbox may be checked and unhacked later on edit.
This how I would do it.
Note: make sure to read the comment
javascript
$("#EditGarageBtn").click(function() {
var customerNumber = customerNumberOfEditingGarage;
// I assumed that you want name as the int of RequestType eg 1 or 2 that are checked
var garageCrossRequestType = $(".checkbclass:checked").map(function(x) {
return parseInt($(x).attr("name"));
});
name = $("#GarageName").val();
countryId = $("#Country").val();
var garageId = $("#garageId").val();
var contactperson = $("#ContactPerson").val();
var email = $("#Email").val();
$("#EditGarageBtn").hide();
if (name.length > 0 && email.length > 0 && contactperson.length > 0) {
$.ajax({
url: '#Url.Action("EditGarage", "Garage")',
dataType: 'JSON',
data: {
name: name,
countryId: countryId,
garageId: garageId,
contactperson: contactperson,
email: email,
garageCrossRequestType: garageCrossRequestType // here send the checked checkedboxes
},
success: function(data) {
if (data == "Failure") {
toastr["error"]("Error editing Garage");
} else {
toastr["success"]("Garage successfully updated");
customerNumberOfEditingGarage = null;
refreshGrid();
}
},
error: function() {
}
});
} else {
toastr["error"]("Error editing Garage");
}
});
C#
// create an sqlProcedure or something instead of this, this is only to show how it work
// You have to clear all GarageCrossRequestType that containe the current GarageID
// An after insert the newly checked items
new SqlCommand("delete GarageCrossRequestType where GarageID = " + model.GarageId, Connection).ExecuteNonQuery();
List <int> newlist = new List<int>();
if (model.garageCrossRequestType != null)
newlist.AddRange(model.garageCrossRequestType);
foreach(var item in newlist) {
//newlist cant be null becouse you are already in a loop.
// and also newlist is never null
// if (newlist != null)
var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#GarageId", model.GarageId);
// instead of newlist.First() you are looping throw newlist eg checkboxes then it should be item
cmd1.Parameters.AddWithValue("#RequestType", item);
int result = cmd1.ExecuteNonQuery();
if (result == 1)
valid = true;
}
I was trying to do the form submit response, like on submit the form fields should be hidden and to show the thank you message without refreshing the page, but when i click submit the page is getting refreshed and showing the ajax response {"result":"success","data":"{\"message\":[\"sample message\"]}"
tried using Send Email from a Static HTML Form using Google Apps Mail!
(function() {
'use strict';
function getFormData(form) {
var elements = form.elements;
var fields = Object.keys(elements).filter().map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
//formData.formGoogleSend = form.dataset.email || ""; // no email by default
formData.formPage = form.dataset.page || "";
}
function handleFormSubmit(event) {
if (this.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
this.classList.add('was-validated');
} else if (this.checkValidity() === true) {
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
}
function loaded() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener("submit", handleFormSubmit, false);
});
}
document.addEventListener("DOMContentLoaded", loaded, false);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>
I expect to show the thankyou message without refreshing the page but the actual result is the page getting refreshed and showing the Ajax response
move event.preventDefault(); out of the if statement so the default submit action of the form is never triggered. You don't want to do an submit when you do an ajax request since the submit action will navigate to the form action url.
$('.needs-validation').on('submit', handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
if (this.checkValidity() === true) {
//Do this in the ajax succes event handler
$('.thankyou_message').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>
I am trying to store the users name, email and their message on my contact page. When i run my website and go on the contact page and type all the details inside the contact form and click the send button (send button called submitBtn) i get the error you can see below in the image.
error message:
c# code: this c# code is for the send button.
protected void submitBtn_Click(object sender, EventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(ConfigurationManager.ConnectionStrings["Fasthosts_MMConnectionString"].ConnectionString);
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into Contact(UserName, Email, Message) " +
"values(#UserName, #Email, #Message)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#UserName", tbUserName.Text);
com.Parameters.AddWithValue("#Message", userMessage.Text);
com.Parameters.AddWithValue("#Email", userEmail.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
//throw Exception ;
Response.Write("Error Message: " + problem.ToString());
throw;
}
}
html code:
<div id="contactForm" class="contactForm">
<div id="formHeader" class="formHeader">
<h1 id="message">Contact Us :)</h1>
</div>
<div id="formBody" class="formBody">
<form action="homepage.aspx" method="POST" name="contactForm">
<div class="inputContainer">
<label for="userName">
<i class="fa fa-lg fa-fw fa-user"></i>
</label>
<asp:TextBox ID="tbUserName" placeholder="John Smith" runat="server"></asp:TextBox>
<!--<input name="name" id="userName" type="text" placeholder="John Smith">-->
</div>
<div class="inputContainer">
<label for="userEmail">
<i class="fa fa-lg fa-fw fa-envelope"></i>
</label>
<asp:TextBox ID="userEmail" placeholder="jsmith#domain.com" runat="server"></asp:TextBox>
</div>
<div class="inputContainer">
<asp:TextBox ID="userMessage" rows="10" placeholder="Enter your message" runat="server" Height="100px"></asp:TextBox>
</div>
<!--<input id="submitBtn1" class="submitBtn" type="submit" value="Send">-->
<asp:Button ID="submitBtn" Class="submitBtn" runat="server" Text="Send" OnClick="submitBtn_Click" />
</form>
</div>
javascript code :
(function () {
"use strict";
var //GLOBAL VARIABLES
input,
container,
//CSS CLASSES
classSuccess = "success",
classError = "error",
//FORM VALIDATOR
formValidator = {
init: function () {
this.cacheDom();
this.bindEvents();
},
cacheDom: function () {
//MAIN PARENT ELEMENT
this.contactForm = document.getElementById("contactForm");
//MAIN FORM ELEMENTS
this.formHeader = document.querySelector("#formHeader h1");
this.formBody = document.getElementById("formBody");
this.inputContainer = document.getElementsByClassName("inputContainer");
//USER INPUT ELEMENTS
//INPUT FIELDS
this.fields = {
userName: document.getElementById("userName"),
userEmail: document.getElementById("userEmail"),
userMessage: document.getElementById("userMessage")
};
this.submitBtn = document.getElementById("submitBtn");
},
bindEvents: function () {
var i;
//RUN RULES ON SUBMIT BUTTON CLICK
this.submitBtn.onclick = this.runRules.bind(this);
//BIND EVENTS TO EACH INPUT FIELD
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//VARIABLES
input = this.fields[i];
container = input.parentElement;
//RUN RULES WHEN INPUT HAS FOCUS
input.onfocus = this.runRules.bind(this);
//RESET ERRORS WHEN CONTAINER IS CLICKED
container.onclick = this.resetErrors.bind(this, input);
}
}
},
runRules: function (evnt) {
var target = evnt.target,
type = evnt.type;
//IF EVENT ON SUBMIT BUTTON
if (target === this.submitBtn) {
//PREVENT FORM SUBMITTION
this.preventDefault(evnt);
//IF INPUT HAS FOCUS
} else if (type === "focus") {
//RESET CLASSLIST
this.resetClassList(target.parentElement);
//RESET ERRORS
this.resetErrors(target);
return false;
}
//RESET CLASSLIST
this.resetClassList();
//CHECK FIELDS
this.checkFields();
},
preventDefault: function (evnt) {
//PREVENT DEFUALT
evnt.preventDefault();
},
checkFields: function () {
var i,
validCount = 0,
//EMAIL FILTER
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//CYLCE THROUGH INPUTS
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
input = this.fields[i];
//CHECK IF FIELD IS EMPTY
if (input.value === "") {
//ADD ERROR CLASS
this.addClass(input, classError);
//CHECK IF EMAIL IS VALID
} else if (i === "userEmail" && !filter.test(input.value)) {
//ADD ERROR CLASS
this.addClass(input, classError);
} else {
//FIELD IS VALID
this.addClass(input, classSuccess);
validCount += 1;
}
}
}
//IF ALL FEILDS ARE VALID
if (validCount === 3) {
//SUBMIT FORM
this.submitForm();
}
},
addClass: function (input, clss) {
container = input.parentElement;
//IF INPUT HAS ERROR
if (clss === classError) {
//SHOW ERROR MESSAGE
this.errorMessage(input);
}
//ADD CLASS
input.parentElement.classList.add(clss);
},
errorMessage: function (input) {
var message;
//IF USERNAME HAS ERROR
if (input === this.fields.userName) {
message = "Please enter your name";
//ELSE IF USEREMAIL HAS ERROR
} else if (input === this.fields.userEmail) {
message = "Please enter a valid email";
//ELSE IF USERMESSAGE HAS ERROR
} else if (input === this.fields.userMessage) {
message = "Please enter your feedback";
}
this.renderError(input, message);
},
renderError: function (input, message) {
var html;
//GET INPUT CONTAINER
container = input.parentElement;
//RENDER HTML
html = document.createElement("div");
html.setAttribute("class", "message");
html.innerHTML = message;
//IF MESSAGE ELEMENT DOESN'T EXIST
if (!container.getElementsByClassName("message")[0]) {
//INSERT MESSAGE TO INPUT CONTAINER
container.insertBefore(html, container.firstElementChild);
}
},
resetClassList: function (input) {
var i;
//IF TARGETING SPECIFIC INPUT
if (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//REMOVE CLASSES
container.classList.remove(classError, classSuccess);
//FOCUS ON INPUT FIELD
input.focus();
} else {
for (i in this.fields) {
if (this.fields.hasOwnProperty(i)) {
//REMOVE CLASSES FROM ALL FIELDS
this.fields[i].parentElement.classList.remove(classError, classSuccess);
}
}
}
},
resetErrors: function (input) {
//GET INPUT CONTAINER
container = input.parentElement;
//IF CONTAINER CONTAINS ERROR
if (container.classList.contains(classError)) {
//RESET CLASSES
this.resetClassList(input);
}
},
submitForm: function () {
var waitForAnimation;
//ADD SUCCESS CLASS
this.contactForm.classList.add(classSuccess);
//WAIT FOR ANIMATION TO FINISH
this.changeHeader("Sent Succesfully");
//WAIT FOR ANIMATION TO FINISH
setTimeout(
this.changeHeader.bind(this, "Thank you for your feedback"),
1200
);
},
changeHeader: function (text) {
//CHANGE HEADER TEXT
this.formHeader.innerHTML = text;
}
};
//INITIATE FORM VALIDATOR
formValidator.init();
})();
Write this in first line of page directive in source code
<%# Page EnableEventValidation="false" %>
On my .html
<div class="col-md-9 col-sm-9 col-xs-12">
<div class="">
<label>
<input type="checkbox" id="SMSCheckbox" class="js-switch" /> SMS
</label>
</div>
<div class="">
<label>
<input type="checkbox" id="EmailCheckBox" class="js-switch" /> Email
</label>
</div>
</div>
On my .js
$(document).ready(initialize);
function initialize() {
console.log("loaded JS");
$.ajax({
type: "GET",
url: "./getNotificationSettings.php",
datatype: "json",
success: function(response) {
var response = JSON.parse(response);
var bySMS = response[0].receiveSMS;
var byEmail = response[0].receiveEmail;
if (bySMS) {
console.log("bySMS = true");
$('#SMSCheckbox').prop('checked', true);
} else {
console.log("bySMS = false");
$('#SMSCheckbox').prop('checked', false);
}
if (byEmail) {
console.log("byEmail = true");
$('#EmailCheckBox').prop('checked', true);
} else {
console.log("byEmail = false");
$('#EmailCheckBox').prop('checked', false);
}
},
error: function(e) {
console.log(e);
}
});
}
bySMS = true
byEmail = true
I checked my console that it does go inside the if true branch but somehow my checkbox is not being selected. It's strange that I tested it on jsfiddle and it's working.
What could be the cause of this strange issue?
Not sure if it matters that to toggle the checkbox, I had to click on the wording. Clicking on the switch doesn't toggle it.
I always use .click() on checkboxes when changing the checked property doesn't work for some reason, not sure if this is a proper way of doing it.
I created a little function to handle it for you:
$.fn.setCheckbox = function(value) {
var checked = $(this).attr("checked") != "undefined" &&
($(this).attr("checked") === "checked" ||
$(this).attr("checked") === true);
if (checked != value) {
$(this).click();
}
}
Plunker: https://plnkr.co/edit/mdAzNsZnRdl2ifIT22e0?p=preview
I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.