How to perform validation for Onclick Javascript Custom button - javascript

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

Related

want to take only one input between 2 input field from html form

I have 2 input in html form. stock in and stock out. In form submission it send st_in and st_out to server with request.
I want-
*if two value(stock_in + stock_out) is submitted system should through error.
*If no value submitted(stock_in + stock_out) system should through error.
*Either "stock in" or "stock out" value should submit then the save method will store the data.
public function stock_record(Request $request){
$stock=new Transection;
$stock->in=$request->st_in;
$stock->out=$request->st_out;
$stock->product_id=$request->st_name;
$stock->barcode=$request->barcode;
$stock->description=$request->st_description;
$stock->user_id=Auth::id();
$stock->save();
return redirect('dashboard')->with('message',"Transection successfully updated");
}
public function stock_record(Request $request){
if($request->st_in == null && $request->st_out == null)
{
return back()->withError('Error ...');
}
if($request->has('st_in') && $request->has('st_out'))
{
return back()->withError('Error ...');
} else if($request->has('st_in') || $request->has('st_out))
{
$stock=new Transection;
$stock->in=$request->st_in ?? null;
$stock->out=$request->st_out ?? null;
$stock->product_id=$request->st_name;
$stock->barcode=$request->barcode;
$stock->description=$request->st_description;
$stock->user_id=Auth::id();
$stock->save();
return redirect('dashboard')->with('message',"Transection successfully updated");
}
}
It's working Now
public function stock_record(Request $request)
{
if ($request->st_in == null && $request->st_out == null) {
return back()->with('message', "you didn't either fill stock in or out");
}
//correction Here
if ($request->st_in > 0 && $request->st_out > 0) {
return back()->with('message', "Error, You cannot fill both stock in and out at a time")
//

Trapping a Cancel in a JavaScript Confirm Prompt?

Something's not working this morning and I'm pretty sure it's my brain. I've got a form that tracks changes to a field under certain conditions:
-If the status = Draft, do nothing.
-If the status = Approved, prompt user to ask if they are sure they want to make the change.
-If they click 'OK', it should call the process that records the change.
-If they click 'Cancel' it should do nothing.
-If the status is anything other than draft or Approved, don't prompt but call the process that records the change.
I had the code recording changes in non-draft status, but after I added the ==true to the end of the confirm statement, everything stopped working.
var stat = $('#status').text();
var parms = just a bunch of parameters i'm passing to the url below;
if (stat=='(Draft)'){
//do nothing
}
else if (stat !== 'Approved' && stat!== '(Draft)'){
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
}
}
else if (stat == 'Approved' && confirm('You are changing the hours on a request that has already been approved. This will send a notification to the department director. Proceed?')==true) {
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
} else {
//do nothing });
}
It is working, but you could just ommit the == true because it already is a "if-able boolean"
if(confirm("test?")){
console.log("confirmed1");
}else {
console.log("notconfirmed1");
}
<!-- or the other way arround -->
if(!confirm("test?")){
console.log("notconfirmed2");
}else {
console.log("confirmed2");
}
<!-- it should also work the way you posted as well -->
if("foo" == "foo" && confirm("test?") == true){
console.log("confirmed3");
}else {
console.log("notconfirmed3");
}

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

On input does not work after preventDefault

I am making simple auth form with some messages for user while he is typing the username/email in the input. Before form submission code works just fine, but after I submit the form (with preventDefault) this 'input-checker' stops working. Can anyone tell me why and how to make it work?:-)
var reValidEmail = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
$("#auth-input").on('input', function () {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
if (!reValidEmail.test(document.getElementById("auth-input").value)) {
$("#login-comment").text("Please enter valid email");
} else {
$("#login-comment").text("");
}
}
});
$("#log-in-form").submit(function (e) {
e.preventDefault();
if ( document.getElementById("auth-input").value.length > 0
&& ( document.getElementById("auth-input").value.indexOf("#") == -1
|| ( document.getElementById("auth-input").value.indexOf("#") + 1
&& reValidEmail.test(document.getElementById("auth-input").value)
)
)
) {
//some ajax request
} else {
if (document.getElementById("auth-input").value.indexOf("#") + 1) {
$("#login-comment").text("Please enter valid email"); //does not hide after form submission and input change for correct one
} else {
$("#login-comment").text("Please enter username or email"); //does not hide after form submission and input change for correct one
}
}
});

How to display error in real-time on HTML form? (Javascript included)

I'm trying to show errors in real time on my registration form, instead of being redirected to another page (register.php).
The index page on my site has a sign-up link which opens a popup registration form (registration.HTML) in a new window. When a user submits this form
it calls on register.PHP as an action. Inside register.php there is a line of code:
js_include('js/register.js');
This javascript checks that certain data is submitted correctly within registration.html. I'd like this check to be performed before submitting the form
and causing it to redirect to register.php. I only need it to direct to register.php if javascript says everything is good.
You can test this yourself here If you click "sign up" in the top-right corner, and type in gibberish as the email and press Enter, it will redirect to register.php and show the error at the bottom (if you scroll down). I'd like this error to be displayed on the registration form.
I tried including the js below within some script tags on my html page, but it still redirects me.
Here is register.js, all feedback is welcome! Thank you
$(document).ready(function() {
$('.formFieldWarning').hide();})
function checkRegisterFormSubmit() {
$('.formFieldWarning').hide();
var errors = 0;
// Check the user name
if($('#username').val() == '') {
$('#username_warning1').show();
errors++;
} else {
if ($('#username').val().length < 2 ) {
$('#username_warning2').show();
errors++;
}
}
// Check the password
if ($('#password').val().length < 2 ) {
$('#password_warning1').show();
errors++;
} else {
if ($('#password').val() == $('#username').val() ) {
$('#password_warning2').show();
errors++;
}
}
// Check the password_verification
if ($('#password_verification').val() != $('#password').val() ) {
$('#password_verification_warning1').show();
errors++;
}
// Check the email address
if($('#email').val() == '') {
$('#email_warning1').show();
errors++;
} else {
if ($('#email').val().search(/^\w+((-|\.|\+)\w+)*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,63}$/) == -1) {
$('#email_warning2').show();
errors++;
}
}
if (errors != 0) {
$('#form_not_submit_top').show();
$('#form_not_submit_bottom').show();
return false;
} else {
return true;
}
}
Here is an example of how to test a form field using jQuery's blur() function -
$('input[name="foo"]').blur(function() {
var currentValue = $(this).val();
var testValue = 'crumple';
if(currentValue != testValue) {
$(this).next('span').html('FAIL');
} else {
$(this).next('span').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="foo" type="text" /><span></span>

Categories