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

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 ...

Related

Email Validation using setCustomValidity

I got the following code for
// Validating Email
function validateEmail() {
var mail = document.getElementById("email").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{3})+$/;
var endEmail = "#gmail"
if(mail.match(mailformat) && (mail.charAt(x.length-1) == endEmail) ) {
mail.value += ".com"
alert(mail)
return true;
} else if (email.validity.valueMissing) {
console.log("Email is missing")
email.setCustomValidity("Please fill in the email.");
}
}
I have a problem with checking the email. The logic I am trying to implement is to check whether the email contains “gmail” after “#” and to validate the email ends in “.com” (This check is only mandatory if the email field has “gmail” after “#”.). In the case of gmail being in the email after “#” and the ending being something other than “.com”, I wanna fix this for the user and let the submission go through after the fix.

Condition for Insert data into database table

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>');
}
}

How to perform validation for Onclick Javascript Custom button

I have the code below and I would like it to perform multiple field validation and give alert on each field when it is incomplete. Scenario: If I use the code without the validation and associated alerts it works 100%, when I include the validation the code goes through each step and alert and ultimately fails on the last bit to execute and flag a field as 'true' and gives error of 'Invalid or unexpected token'. Any help would be welcome
{
!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")
}
var x;
if ('{!Case.Trigger_Submit_Spark__c}' == true || '{!Case.Spark_Service_Desk_Ref__c}' != "") {
alert('You are unable to submit request, as this request has already been submitted to Spark')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as Spark Service Request Type and Request note are blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' == "" && '{!Case.Spark_Request_Note__c}' != "") {
alert('You are unable to submit request, as Spark Service Request Type is blank')
} else {
if ('{!Case.Spark_Service_Request_Type__c}' != "" && '{!Case.Spark_Request_Note__c}' == "") {
alert('You are unable to submit request, as the Spark Request Note is blank')
} else {
if ('{!Case.Trigger_Submit_Spark__c}' == false && confirm('Do you want to submit this request?\n\nBy submitting this request the following will occur:\n 1. Case Status changed to Escalated to Tier2\n 2. Escalation Group = Spark\n 3. Email sent to Spark (Remedy)\n 4. Note placed in SalesForce chatter feed\n\nPlease check chatter feed to confirm that request has been sent') == true) {
x = "OK";
var c = new sforce.SObject("Case");
c.id = '{!Case.Id}'
c.Trigger_Submit_Spark__c = true;
result = sforce.connection.update([c]);
if (result[0].success === "true") {
window.location.reload();
} else {
alert("An Error has occured. Error: " + result[0].errors.message);
}
}
}
}
}
}

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 == "")

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.

Categories