validate form and send data to php page using ajax jquery - javascript

i am trying to send form data to php page before that i wan to validate all required inputs. bellow is my jquery.
$('form#Wall_Post').submit(function(event) {
event.preventDefault();
type = $('.shareType').val();
for (var i = 0; i < formData.length; i++) {
if (!formData[i].value && formData[i].name == 'message') {
alert('Message could not be empty');
return false;
}
if (type == 'photos') {
var fileName = document.getElementById("image").value
if (fileName == "") {
alert("Browse to upload a valid File with png/jpg/gif extension");
return false;
} else if (fileName.split(".")[1].toUpperCase() == "PNG") {} else if (fileName.split(".")[1].toUpperCase() == "JPG") {} else if (fileName.split(".")[1].toUpperCase() == "JPEG") {} else if (fileName.split(".")[1].toUpperCase() == "GIF") {} else {
alert("File with " + fileName.split(".")[1] + " is invalid. Upload a validfile with png/jpg/gif extensions");
return false;
}
}
if (type == 'videos') {
if (!formData[i].value && formData[i].name == 'videoUrl') {
alert('Video Url could not be empty');
return false;
}
video = validateVideoUrl();
if (video == false) {
alert('Not a valid youtube/vimeo video URL');
return false;
}
}
if (type == 'location') {
if (!formData[i].value && formData[i].name == 'location') {
alert('Place could not be empty');
return false;
}
if ((!formData[i].value && formData[i].name == 'lat') || (!formData[i].value && formData[i].name == 'lng')) {
alert('Not a valid place');
return false;
}
}
}
btn = $('#btn-share');
btn.button('loading');
// Prevent the form from submitting via the browser
//var form = $(this);
$('#loading').show();
$.ajax({
url: "/update.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: $('form#Wall_Post').serialize(),
success: function(mesg) // A function to be called if request succeeds
{
$('#loading').hide();
$('.wallupdate').html(mesg);
//alert(mesg);
}
});
});
its working fine before add the validation code. i don't understand where i am doing wrong. I am new to jquery.

Related

Console log for foreach javascript didn't show up

I've been trying to work on some validation in javascript, just a simple one. But, the error can't show up in the console log. If all the inputs are correct, it will show the "Registration success text" but in the other side, it won't show any of the error text. But it somehow still can get the focus function to the wrong input, only the error texts that are not showing up in the console. I am so confused. Can you guys help me? I'd appreciate that.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
if(name.value === ''){
error.push("Name is required.");
name.focus();
return false;
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
name.focus();
return false;
}
if(uname.value === ''){
error.push("Username is required.");
uname.focus();
return false;
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
uname.focus();
return false;
}
if(email.value === ''){
error.push("Email is required.");
email.focus();
return false;
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
return false;
}
if(passw.value === ''){
error.push("Password is required.");
passw.focus();
return false;
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
confpassw.focus();
return false;
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
if(region.value == 0){
error.push("Region is not selected");
region.focus();
return false;
}
if(gender.value == 0){
error.push("Gender is not selected");
gender.focus();
return false;
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
termss.focus();
return false;
}
if(error.length == 0){
alert("Registration Success!");
} else{
for(var i=0; i<error.length; i++){
console.log(error.length[i]);
};
}
}
You are returning too early so it is never reaching your consoles. You are focusing on multiple fields.
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
You are also doing console.log(error.length[i]); instead of console.log(error[i]);.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
let firstFailedField = null;
const setFirstFailedField = (field) => {
if (!firstFailedField) firstFailedField = field;
};
if(name.value === ''){
error.push("Name is required.");
setFirstFailedField(name);
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
setFirstFailedField(name);
}
if(uname.value === ''){
error.push("Username is required.");
setFirstFailedField(uname);
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
setFirstFailedField(uname);
}
if(email.value === ''){
error.push("Email is required.");
setFirstFailedField(email);
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
setFirstFailedField(email);
}
if(passw.value === ''){
error.push("Password is required.");
setFirstFailedField(passw);
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
setFirstFailedField(confpassw);
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
setFirstFailedField(confpassw);
}
if(region.value == 0){
error.push("Region is not selected");
setFirstFailedField(region);
}
if(gender.value == 0){
error.push("Gender is not selected");
setFirstFailedField(gender);
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
setFirstFailedField(termss);
}
if(error.length == 0){
alert("Registration Success!");
return true;
}
error.forEach((err) => (console.log(err)));
if (firstFailedField && typeof firstFailedField.focus === 'function') firstFailedField.focus();
return false;
}

OnClick doesn't work after Jquery validations

I have given validations through jquery which works fine on button click.
But as soon as I fill all the data into the page, my onClick does not fires. I dont know why. Please suggest.
Here is my jquery code:-
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTitle();
validateddl();
validateTextBoxes();
if (ErrArr.length > 0) {
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTitle() {
if ($("#ddlTitle").val() > "0") {
if ($("#ddlTitle").val() == "1104" && $("#txtTitle").val() === "") {
ErrArr.push("Please enter the text in other title");
}
} else {
ErrArr.push('Please select the title');
}
}
function validateTextBoxes() {
if ($("#txt_emp_fname").val() === "") {
ErrArr.push('First name is required');
}
if ($("#txt_emp_mname").val() === "") {
ErrArr.push('Middle name is required');
}
if ($("#txt_emp_lname").val() === "") {
ErrArr.push('Last name is required');
}
if ($("#txtDateofJoin").val() === "") {
ErrArr.push('Date of joining is required');
}
if ($("#txtReligion").val() === "") {
ErrArr.push('Religion is required');
}
if ($("#txtBloodGroup").val() === "") {
ErrArr.push('Blood group is required');
}
if ($("#txtPersonalEmail").val() === "") {
ErrArr.push('Email Id is required');
}
if ($("#txtDtOfBirth").val() === "") {
ErrArr.push('Date of birth is required');
}
if ($("#txtAt").val() === "") {
ErrArr.push('Place of birth is required');
}
if ($("#txtTaluka").val() === "") {
ErrArr.push('Taluka is required');
}
if ($("#txtPostOffice").val() === "") {
ErrArr.push('Post office is required');
}
if ($("#txtDistrict").val() === "") {
ErrArr.push('District is required');
}
if ($("#txtStatePersonal").val() === "") {
ErrArr.push('State is required');
}
if ($("#txtDtMarriage").val() === "") {
ErrArr.push('Date of Marriage is required');
}
if ($("#TxtPassportNo").val() === "") {
ErrArr.push('Passport no is required');
}
if ($("#txtIdMark").val() === "") {
ErrArr.push('Identification mark is required');
}
}
function validateddl() {
if ($("#ddlGender").val === "" || $("#ddlGender").val() == "0") {
ErrArr.push('Please select the gender');
}
if ($("#ddlMaritalStatus").val === "" || $("#ddlMaritalStatus").val() == "0") {
ErrArr.push('Please select the Marital Status');
}
if ($("#ddlNationality").val === "" || $("#ddlNationality").val() == "0") {
ErrArr.push('Please select the Nationality');
}
}
});
Also see my aspx of button:-
<asp:Button ID="btnSave" CssClass="button" Text="Save" runat="server"
CausesValidation="true" onclick="btnSave_Click"
/>
I suggest you do NOT use the click of the button but the submit of the form to validate:
$(document).ready(function () {
$('#formID').on("submit",function (e) {
// e.preventDefault(); // does not belong here
validateTitle();
validateddl();
validateTextBoxes();
if (ErrArr.length > 0) {
e.preventDefault();// but here
alert(ErrArr.join("\n"));
ErrArr = [];
}
});
.
.
.
I assume that also means you should make your button a submit button and make sure the asp does not add a click event since it is already assigned by the jQuery
$('#btnSave').on("click", function(e) {
//e.preventDefault();
validateTitle();
validateddl();
validateTextBoxes();
if(ErrArr.length > 0) {
e.preventDefault(); //use e.preventDefault here
alert(ErrArr.join("\n"));
ErrArr = [];
//return false;
}
});
move event prevent on the button click handler only when client validation fails.
$('#btnSave').click(function (e) {
validateTitle();
validateddl();
validateTextBoxes();
if (ErrArr.length > 0) {
alert(ErrArr.join("\n"));
ErrArr = [];
e.preventDefault();
return false;
}
});
Try this
$('#btnSave').click(function(e) {
//e.preventDefault();
validateTitle();
validateddl();
validateTextBoxes();
if(ErrArr.length > 0) {
e.preventDefault(); //use e.preventDefault here
alert(ErrArr.join("\n"));
ErrArr = [];
//return false;
}
});

jQuery not returning any value

I have some code that checks if the contents of the form is valid. checkEmpty, checkNumeric and checkEmail is working fine if i comment out the checkFile function. But if I include checkFile, it breaks the code causing the function not to return any value.
Here is the checkFile function. It's supposed to check the file extension.
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
Also the function should be working fine. I tried it seperately to see if it gets the extension properly.
Here is the whole code in case its needed
$(window).load(function() {
// validations
$.fn.checkEmpty = function(emp) {
if(emp === ""){
alert("field is empty");
return false;
}else{
alert("not empty");
return true;
}
};
$.fn.checkEmail = function(email) {
var regex = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if(regex.test(email)){
alert("mail is valid");
return true;
} else {
alert("mail is invalid");
return false;
}
};
$.fn.checkNumeric = function(value) {
// 10 digits for phone number ?
/*
if (value.length !== 10 || value === "" || !$.isNumeric(value)) {
alert("not a numerical value");
} else {
alert("numerical value");
}*/
var regex =new RegExp(/^(?:\d*\,\d*|\d+)$/);
if(regex.test(value) && value!==""){
alert("numerical value");
return true;
} else {
alert("not numerical value");
return false;
}
};
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
$.fn.checkField = function() {
var empty = "empty";
var numeric = "numeric";
var email = "email";
var file = "file";
var flag=0;
var retval;
$("input:text").each(function() {
var required = $(this).data("reqs");
if(required.toLowerCase().indexOf(empty) !== -1){
retval = $(this).checkEmpty($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if (required.toLowerCase().indexOf(numeric) !== -1){
retval = $(this).checkNumeric($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if(required.toLowerCase().indexOf(email) !== -1){
retval = $(this).checkEmail($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
$("input:file").each(function() {
if(required.toLowerCase().indexOf(file) !== -1){
retval = $(this).checkFile($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
alert(flag);
return (flag > 0) ? false : true;
};
});
Thanks for any help.
As Bergi pointed it out, it doesn't make much sense to add the function to the prototype if you pass it the filename as a parameter...
However, adding it to the prototype can be a good idea if you actually use this within the method:
$.fn.checkFile = function(){
var filename = $(this).val();
if (/(?:jpe?g|docx|pdf|xlsx)$/.test(filename)){
return true;
}else{
return false;
}
};
You can test this method at http://jsfiddle.net/NVvzN/. Try choosing different files from your computer to see how it works.
PS: my guess is, if you accept .docx and .xlsx, you should also accept .doc and .xls; in that case, the regular expression would be /(?:jpe?g|docx?|pdf|xlsx?)$/

convert condition into function javascript

I have a function to validate data from a form:
var step1_validation = function(){
var err = 0;
if($('#one').val() == '0'){
$('#one').parent().parent().find('.form-error').html("display error for one.");
err++;
}
if($('#other').val() == '0'){
$('#other').parent().parent().find('.form-error').html("display error for other.");
err++;
}
if($('#eda').val() == ''){
$('#eda').parent().parent().find('.form-error').html("display error for one eda.");
err++;
}
if(err == 0){
//do something
}else{
//do other stuff
}
};
As there are several inputs I would like to validate How can I make a function to verify input is 0 or empty string, and call it inside my function?
if($('#id').val() == '0'){
$('#id').parent().parent().find('.form-error').html("display message.");
err++;
}
or
if($('#id').val() == ''){
$('#id').parent().parent().find('.form-error').html("display message.");
err++;
}
Like this?
var step1_validation = function () {
var err = 0;
err += validateInput('one', 'display error for one.');
err += validateInput('other', 'display error for other.');
err += validateInput('eda', 'display error for eda.');
if (err == 0) {
//do something
} else {
//do other stuff
}
};
function validateInput(id, errorMessage) {
var obj = $('#' + id);
if (obj.val() == '0' || obj.val() == ''){
obj.parent().parent().find('.form-error').html(errorMessage);
return 1;
}
return 0;
}

Javascript Focus Is Not Working on Aspx Page

Hy Guys,
Please Look at the code and Try to Help Out. The function ive written is not working but its RUNNING properly. Its about To set focus on next content on page im using it on an ASPX page. Heres my code Below :
function SetFocusOnSave(CTag,NTag)
{
alert('Running'+CTag+NTag);
var CurrentTag=document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ( (event.keyCode==13)||(event.keyCode==9) )
{
if(CurrentTag.value=="")
{
alert("Please Enter Detail First");
CurrentTag.focus();
}
if(CurrentTag.value!="")
{
event.returnValue=true;
document.getElementById(NextTag).focus();
}
}
}
snametxt.Attributes.Add("onkeypress",
SetFocusOnSave('<%=snametxt.ClientID%>','<%=sdesctxt.ClientID%>');");
have you tried to replace
document.getElementById(NextTag).focus();
with
NextTag.focus();
?
You have to add return false; after you found the false in validation otherwise the flow will continue till end.
Try this function:
function SetFocusOnSave(CTag, NTag) {
alert('Running' + CTag + NTag);
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ((event.keyCode == 13) || (event.keyCode == 9))
{
if (CurrentTag.value == "")
{
alert("Please Enter Detail First");
CurrentTag.focus();
return false;
}
if (CurrentTag.value != "") {
event.returnValue = true;
NextTag.focus();
return false;
}
}
};
Hy Guys Ive Tried A NEW CODE AND Fortunately Its Working Fine Here its my Code
function Navigation(CTag, NTag, Number) {
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
var IsNumber = Number; //Checking if value is number
if (NextTag.disabled == true) {
NextTag.disabled = false;
NextTag.className = "txt";
}
if (event.keyCode == 9) {
CurrentTag.focus();
event.returnvalue = false;
}
if (event.keyCode != 9) {
if (event.keyCode == 13) {
if (IsNumber == "Y") {
if (NextTag.disabled == true) {
NextTag.disabled = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (isNaN(CurrentTag.value)) {
alert("Please Enter A Valid Number");
CurrentTag.value = "";
CurrentTag.focus();
}
}
if (IsNumber == "N") {
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
}
}
}
};
Thanks ya'll !! :)

Categories

Resources