Condition for Insert data into database table - javascript

New to Js and stuck here. What should I put into my if statement to insert data into database table? Because right now I do get intended error message when I submit a wrong value but it still inserts it to database. Appreciate the help!
Here is my index.js
var manageMemberTable;
$("#addMemberModalBtn").on('click', function() {
// reset the form
$("#createMemberForm")[0].reset();
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".messages").html("");
// submit form
$("#createMemberForm").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
var form = $(this);
// validation
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
this is what I'm checking
if (firstname == "") {
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
else {
if (firstname.match(/^[a-zA-Z ]+$/) === null){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">Firstname invalid</p>');
}
else {
$("#firstname").closest('.form-group').removeClass('has-error');
$("#firstname").closest('.form-group').addClass('has-success');
}
}
//lastname validation
if (lastname == "") {
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
else {
if (lastname.match(/^[a-zA-Z ]+$/) === null){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
else {
$("#lastname").closest('.form-group').removeClass('has-error');
$("#lastname").closest('.form-group').addClass('has-success');
}
}
And this is the i statement
if( // Something that checks the submitted data meets requirements) {
//submit the form to server
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType : 'json',

This can be one approach.
firstname.match(/^[a-zA-Z ]+$/) returns true if the string matches the regular expression
if ((firstname != "") && (firstname.match(/^[a-zA-Z ]+$/)) &&
(lastname != "") && (lastname.match(/^[a-zA-Z ]+$/))) {
$("#firstname").closest('.form-group').addClass('has-success');
$("#lastname").closest('.form-group').addClass('has-success');
// code to send data to database
}
else {
if(firstname === ""){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">The firstname field is required</p>');
}
if (!firstname.match(/^[a-zA-Z ]+$/)){
$("#firstname").closest('.form-group').addClass('has-error');
$("#firstname").after('<p class="text-danger">firstname is invalid</p>');
}
if(lastname === ""){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">The lastname field is required</p>');
}
if (!lastname.match(/^[a-zA-Z ]+$/)){
$("#lastname").closest('.form-group').addClass('has-error');
$("#lastname").after('<p class="text-danger">lastname is invalid</p>');
}
}

Related

validating reCaptcha in javascript function that get called on submit. (ASP classic)

I need help in validating the response of ReCaptcha in javascript validation which is made for other validations like, n Field is empty etc..
The javascript function function verify(f) {....} get called on onSubmit="return verify(this);" in html <form name="form2" method="POST" action="alink.asp" onSubmit="return verify(this);">
Bellow is the complete js function:
function verify(f) {
var msg = '';
var s = f.CKRoutingNumber.value;
s = s.replace(/[^0-9]/gi, "");
f.CKRoutingNumber.value = s;
if (f.CustomerID.value == '') { msg = 'Please enter your Bricks R Us Customer ID.'; f.CustomerID.focus(); }
else if (f.PurchaseOrderNumber.value == '') { msg = 'Please enter the purchase order number.'; f.PurchaseOrderNumber.focus(); }
else if (f.Amount.value == '') { msg = 'Please enter the amount you wish to pay.'; f.Amount.focus(); }
else if (f.CKBankName.value == '') { msg = 'Please enter a value into the Bank Name field.'; f.CKBankName.focus(); }
else if (f.CKRoutingNumber.value == '') { msg = 'Please enter a value into the Routing Number field.'; f.CKRoutingNumber.focus(); }
else if (s.length != 9) { msg = 'Please enter a valid nine-digit routing/transit number.'; f.CKRoutingNumber.focus(); }
else if (f.CKAccountNumber.value == '') { msg = 'Please enter a value into the Account Number field.'; f.CKAccountNumber.focus(); }
else if (f.CKNumber.value == '') { msg = 'Please enter a value into the Check Number field.'; f.CKNumber.focus(); }
else if (f.BillingName.value == '') { msg = 'Please enter a value into the Full Name field.'; f.BillingName.focus(); }
else if (f.BillingAddress.value == '') { msg = 'Please enter a value into the Billing Address field.'; f.BillingAddress.focus(); }
else if (f.BillingCity.value == '') { msg = 'Please enter a value into the Billing City field.'; f.BillingCity.focus(); }
else if (f.BillingState.value == '') { msg = 'Please select a value for the Billing State field.'; f.BillingState.focus(); }
else if (f.BillingZIPCode.value == '') { msg = 'Please enter a value into the Billing ZIP Code field.'; f.BillingZIPCode.focus(); }
else if (f.BillingPhone.value == '') { msg = 'Please enter a value into the Phone Number field.'; f.BillingPhone.focus(); }
if (msg != '') {
alert(msg);
return false;
}
}
The above function is on the same page in which the form is made.
Bellow is the ASP classic code which get response from reCaptcha. Its also on the same page
<%
Dim reresponse
reresponse= Request.form("g-recaptcha-response")
Dim VarString
VarString = _
"?secret=6Lex3CMTAAAAAASVS5XnIq4Ya5ZGvEH_W70NU&" & _
"&response=" & reresponse & _
"&&remoteip=" & Request.ServerVariables("REMOTE_ADDR")
Dim url
url="https://www.google.com/recaptcha/api/siteverify" & VarString
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "POST", url, False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send
Dim ResponseString
ResponseString = objXmlHttp.responseText
Set objXmlHttp = Nothing
If instr(ResponseString, "success" & chr(34) &": true")>0 then
// do nothing
else
// Here I want to get this response message and validate it in the above javascript function.
end if
%>
I'm confused that how can I get the response from asp and validate it in the verify(f) javascript function so that I also get alert message on submit button that the recaptcha is required and or incorrect.
My intention is to validate the reCaptcha response in same veryify javascript function which get called on submit and shows validation in alert()
Remember, both asp code and javascript code are in the same page.
Please ask if you also need my form html code
Your verify() function is running locally and doing some input value checking/alerting is OK, but in any case you should check whatever comes from the browser on de server side. If you would send the ReCaptscha response back to that verify() function you undermine your security because your users could simple change that verify() function ...

Function is called but it not shows error for repassword validation. Function is called by onBlur event

function repasswordvalid()
{
var cpassword = document.registration.repassword.value;
var passwordchk = document.registration.password.value;
if((passwordchk != cpassword) && cpassword == "")
{
alert("Cofirm password not matched..!!");
document.getElementById('repassword1').innerHTML = "The password is required.";
document.getElementById('repassword1').focus();
}
else
{
document.getElementById('repassword1').innerHTML = "";
}
}
Here I am checking for confirm password validation onBlur event. All fields are working but here i am stuck.
You probably want an or in your condition not an and, since the cpassword will have to be blank and both field mismatched for the alert to trigger
if((passwordchk != cpassword) || cpassword == "")

Trying to redirect to page on click

No expert when it comes to JS/Jquery, but im trying to use this code, and once the registration sign up is done correctly, and the information is stored, instead of a alert box, i wanna have it redirect to another web page... This is what ive got so far, ive tried a few things, but none seem to be working... What am i doing wrong, and how to fix this?
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
if (data == "index.html"){
//...
}
Stripped version.
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
// check if registration ok
location.href = 'index.html';
});
});
});

Validation of registration form with AJAX and JSON

I have a Username field in my registration form. When the user hits the Submit button, it should check if the username is not empty and that such username doesn't exist yet. So I have these functions:
function register() {
var userName = checkIsUsernameExist();
var passwordMatch = checkPasswordMatch();
if(userName && passwordMatch){
$.getJSON("inc/API.php",
{
command : "register",
username : $("#txtNewUsername").attr("value"),
password : $("#txtNewPassword").attr("value"),
email : $("#txtEmail").attr("value"),
phone : $("#txtPhone").attr("value")
},
function ()
{
$("#divIsRegFormValid").removeClass("registrationFormAlert");
$("#divIsRegFormValid").addClass("registrationFormConfirm");
$("#divIsRegFormValid").html("Thank you for registering!");
}
);
} else {
$("#divIsRegFormValid").removeClass("registrationFormConfirm");
$("#divIsRegFormValid").addClass("registrationFormAlert");
$("#divIsRegFormValid").html("Some errors occured. Please register again.");
}
}
function checkIsUsernameExist(){
if($("#txtNewUsername").attr("value") == "") {
$("#divIsUsernameExist").html("");
return false;
} else {
$.getJSON("inc/API.php",
{
command : 'isUsernameExist',
username : $("#txtNewUsername").attr("value")
}).done(
function(result)
{
if (result != true){
$("#divIsUsernameExist").removeClass("registrationFormAlert");
$("#divIsUsernameExist").addClass("registrationFormConfirm");
$("#divIsUsernameExist").html("This username is available!");
return true;
} else {
$("#divIsUsernameExist").removeClass("registrationFormConfirm");
$("#divIsUsernameExist").addClass("registrationFormAlert");
$("#divIsUsernameExist").html("This username is not available!");
return false;
}
});
}
}
At this moment I only receive False if the username is empty, and if it's not - I get Undefined (checked it with some Alert commands). So how can I make it work and return True or False if the username is entered and it's been checked if such username already exist or not?
Thank you!
.val() is prefered $("#txtEmail").attr("value") => $("#txtEmail").val() ;)
You get undefined probably because there is no value attribute in your html use $('#txtEmail').val() instead.

passing form info when created dynamically with javascript

I am trying to pass a user name and password through a dynamically created form but it's not doing so. Here's the JS. The dynamically created form is only if the url contains certain url stems ( location.pathname...3rd "if" statement) Any ideas? It's driving me crazy.
function PostToAccountManagement() {
var userName = $('#Username').val();
var passWord = $('#Password').val();
if (userName == "")
$('#UsernameError').html('Please enter a valid username');
else
$('#UsernameError').html('');
if (passWord == "")
$('#PasswordError').html('Please enter a valid password');
else
$('#PasswordError').html('');
if (location.pathname.search(/\/info/i) == 0 ||
location.pathname.search(/\/blogs/i) == 0 ||
location.pathname.search(/\/groups/i) == 0 ||
location.pathname.search(/\/askquestion/i) == 0) {
$('<form id="Form1"> </form>').prependTo('body');
if (userName != "" && passWord != "") {
document.cookie = "ReturnUrl" + "=" + window.location.href;
$('#Form1').eq(0).attr('action', '/account/logon');
$('#Form1').eq(0).attr('method', 'post');
$('#Form1').submit();
}
}
if (userName != "" && passWord != "") {
document.cookie = "ReturnUrl" + "=" + window.location.href;
$('#Form1').eq(0).attr('action', '/account/logon');
$('#Form1').eq(0).attr('method', 'post');
$('#Form1').submit();
}
}
First the form you creates in the 3rd "if". Looks like you already have a form with id "Form1", this is not good.
Second you can't get the username and password when the 3rd "if" is triggered because the form you submit don't have elements named like that, it actually have none. Try adding at least some hidden inputs properly named.

Categories