Is there a way to natively validate the customer form fields with Square? - validation

I am using PHP Connect to submit a simple payment via Square. I’ve added a customer object, but do not see any validation settings for fields with the customer object via Square’s API. There must be a way to set custom required fields when dealing with a customer object. Can someone please point me the right way?
Here is the PHP script I am using to connect to Square:
https://github.com/square/connect-api-examples/blob/master/connect-examples/v2/php_payment/index.php
As you can see, there is an onclick event in the button submit:
<button id="sq-creditcard" class="sq-button" onclick="requestCardNonce(event)">
I can remove this event and validate fields via jQuery, but I am having trouble when attempting to run the event on successful validation. Here is one example I have tried:
$(“form”).submit(function(){
$(“input”).each(function(){
if($(this).val()){
good = true;
}else{
good = false;
}
});
if(good){
requestCardNonce(event);
}
});
This is just a stripped down version of what I am attempting. Essentially, just passing the requestCardNonce(event) after everything checks out. But when I do this, it breaks...

Related

Payment method form not visible before click

We have created custom payment method. The method contains inputs etc in its form.phtml file. In checkout, we get to Payment methods and our method is checked, but its form is not visible until we check it again. We can click continue, but it throws exception that we need to fill those inputs. However, user does not see them so he'll be confused.
Real situation
Expected situation
Do we need to add any property?
Solution:
I added JS to form.phtml and it is working now.
var customMethodCheckbox document.getElementById("p_method_custom_method");
var customForm = document.getElementById("payment_form_<?php echo $this->getMethodCode() ?>");
if(customMethodCheckbox.checked){
customForm.style.display = "";
}
Once form.phtml is loaded, it triggers this JS. If custom payment method is checked as default, it removes display: none attribute from custom form and displays it. And you don't need to worry about changing payment methods etc, because it is solved by Magento.

File upload validation in xPages

According to this article
http://www-10.lotus.com/ldd/ddwiki.nsf/revisions/6A9EDD911827AA13852574EA00388F8F?OpenDocument
simple validation should work for File Upload controls. I am trying to use it in a extLib Form table.
I would like to verify that the user have selected a file, but have not been able to get this to work on serverside validation. Have also tried to use a custom validator, but still with no luck. Other required fields are marked fine, but not the upload control.
Do anyone know how validate that the user have actually selected a file?
The validation works for client side validation only. There are some workarounds:
The easiest way to validate if a file was attached is to add a validation field to your form and set the property computeWithForm="onsave" of your datasource. As soon as you want to save the document a validation error is thrown and the saving is interrupted. The validation field is a simple editable field with a validation formula like this:
#If(#Attachments = 0;#Failure("No File attached!");#Success)
Check your datasource in the querySave event:
if( document1.getAttachmentList("Body").isEmpty() ){
var msg = new javax.faces.application.FacesMessage("No File added!");
facesContext.addMessage( "No File!", msg );
return false;
}
These two workarounds are only working if the document is newly created. As soon a file is attached, these two options are not working anymore.
If you want to check already existing documents, you can use this XSnippet here:
http://openntf.org/XSnippets.nsf/snippet.xsp?id=replace-attachment-when-uploading-a-new-attachment
You then have to modify the XSnippet to fit your requirements and add a message (as shown in the second example).
Hope this helps
Sven
I'm aware that this has been asked and answered several months ago, but I was looking for an answer to the same problem today when I found this.
Although Sven's answers didn't help directly, option #2 gave the final hint to my solution. Maybe it can be of use for others, too:
First of all, my page uses a standard button (not a button of type "Submit" as I need to set some hidden fields along with the editable ones). So, before the final saving is done I added this script to my button code:
var numAtts = myDocDatasource.getAttachmentList("Body").size();
if(numAtts == 0){
var msg = new javax.faces.application.FacesMessage("You need to attach a file");
facesContext.addMessage("File validation error", msg);
return false;
}
//do some more stuff
...
myDocDatasource.save();
I had to realize that the content of the fileUpload control doesn't really matter when it comes to validation as at that stage of the process an uploaded file already is part of the datasource.
The "timing" of this validation step is a bit surprising, though: at least in my situation, validation of other fields is done before the file upload is validated:
in an errorMessages control first only the standard validation errors are listed. Only after all the other fields have been validated successfully my fileUpload validator is displaying its error.

View that hides/shows controls

I am in the process of porting a site I wrote from ASP.NET webforms to MVC3 and need some guidance as outlined below. I'm new to MVC3.
In my existing ASP.NET web forms project I have a simple page where the user enters a username, they then click a button which causes a postback, on postback there is some basic code that checks if the entered username exists in a user repository - if it does, a textbox containing the users e-mail is shown and the username textbox is made invisible. This happens with ajax and so when the username is entered, the textbox containing the e-mail along with an "Update" button is shown without a full page refresh.
I created a model such as:
public class ChangeEmailModel
{
[Required]
public string Username { get; set; }
[Required]
public string Email { get; set; }
}
Problem is that when the user first enters the page, they should only see a textbox prompting them to enter a username. Once the username is entered and an update button clicked, only then their e-mail is shown (retrieved from the database). Once the e-mail is shown, they can edit the e-mail and click update, which then will need to post to a controller action that saves the updated e-mail. I'm not yet fully used to thinking in the MVC way, so I'm not sure if I've started on the wrong foot with the model above...
Can someone give me some guidance on how this can be accomplished in MVC3 so I can give it a try?
I will start off by suggesting that you start using JQuery for your javascript/ajax functions. ASP.Net MVC3 supports JQuery nicely. I will ignore validation of the email for now as it will be much easier to get you started without it. A high level overview will be:
Add the JQuery script to your page
Add the JQuery vsdoc script to your page so you have some intellisense
Create a partial view to show the email and submit button
Create a controller action that performs the email lookup you mentioned
Create a div to accept the newly returned Email Update form
Use JQuery to override the submit on your username lookup to perform an ajax update instead (and populate the Email Update form div)
1. Add the JQuery script to your page
This should be pretty easy - just drag it from your scripts folder. I think mvc3 comes with jquery-1.5.1.js. Use the min (minified) version when you release to production.
2. Add the JQuery vsdoc script to your page so you have some intellisense
Not quite as easy here - you will want to use an if statement that always evaluates to false so the script is not actually included in your content. Having it on the page though, will cause VS to use it for intellisense. Put this near the top of your view:
#if (false) { <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script> }
Hopefully you are using Razor. If not, start using it. It seemed a little foreign to me at first, but it requires much less markup.
3. Create a partial view to show the email and submit button
You could use the ViewBag to pass the Email address and UserName (for now as we are ignoring validation), but go ahead and make it strongly typed to your Model from above. Your view may look something like this:
#model ChangeEmailModel
#{using (Html.BeginForm("UpdateEmail", "Home", FormMethod.Post, new { id = "UpdateEmailForm" }))
{
<input type="hidden" name="userName" value="#Model.UserName" />
#Html.EditorFor(m => m.Email)
<button id="submitEmailUpdate" type="submit">Submit</button>
}
}
Note that we have given Ids to the form and the submit button. JQuery will find the form and button based on these ids. (if we need to, which we will if we want to "ajaxify" the action of updating the email. I did not go into that detail here, but it will be the same process to get that working as it is for the original username lookup)
4. Create a controller action that performs the email lookup you mentioned
I won't go into controllers much here (as you are asking about ajax type updates) but it might look like:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LookupEmail(string userName)
{
//connect to db and lookup email based on passed in username
//create a new instance of your model
var changeEmailModel = new ChangeEmailModel(.....)
//return a partial view
return PartialView("EmailUpdateForm", changeEmailModel);
}
Make sure to return a PartialView here rather than a View.
5. Create a div to accept the newly returned Email Update form
Make sure this div is not contained in your Username lookup form (as you want to hide it). We will be working with two separate forms. This div could be hidden if you prefer (but will start out empty anyway) I am calling it emailFormDiv
6. Use JQuery to override the submit on your username lookup to perform an ajax update instead
JQuery will allow you to attach functions to... well a lot of things, but we will be using it to override the submit button on your username lookup form. Assume that your original username lookup form with an id of "formUserNameLookup" that has a submit button with an id of "submitUserNameLookup". You would then create a script tag that looks something like this:
<script type="text/javascript" language="javascript">
$(document).ready(function () { //The document.ready function will fire when the html document is... ready
$('#submitUserNameLookup').click(function (ev) { //fires when the submit button is clicked
ev.preventDefault(); //prevent the normal action of the button click
$.post($('#formUserNameLookup').attr('action'), //get the url from the form's action attribute. Could be hard coded for simplicity
$('#formUserNameLookup').serialize(), //serialize the data in the form
function (response, status) {
$('#emailFormDiv').html(response); //replace the html of your div with the response
$('#formUserNameLookup').hide(); //hide the original form
}, 'html'); //states that we are expecting html back from the post
});
});
</script>
The code above is attaching a function to be run when the submit button is clicked. It won't run, of course, until the button is actually clicked. Using JQuery/Javascript to attach functions to html elements, rather than embedding them directly inside the element is definitely preferred, and is referred to as unobtrusive javascript. If you continue with ajaxifying more of your page, you will want to look into JQuery's live and/or delegate functions. Note that there are plenty of things that can be changed once you start looking toward performance and/or best practices. The above should get you going though. I hope I haven't made too many assumptions on your current level of familiarity with ASP.Net MVC (like controllers and posting to controllers) but by all means, ask if you need further help.

How to force form client-side validation in or before $.ajax()

I have a form and unobtrusive validations are enabled. By default in submit method client side validation gets triggered and (if you have any errors) the form looks like this:
The validation happens even before any data gets sent to the server.
Now this behavior doesn't work if you want to use $.ajax method. Client side validation doesn't work. You have to manually check all the fields in your javascript, losing all the beauty of DataAnnotations.
Is there any better solution? I could've use jquery's submit() but I guess it doesn't have callback like $.ajax.
Oh...
if (form.valid()) // do submit
You must force the form to validate before checking if it is valid. Something like this:
var form = $( "#myform" );
form.validate();
if (form.valid()) {
// ...
}
I did...
$("#form-submit-button").click(function (e) {
e.preventDefault(); // Stops the form automatically submitting
if ($("#my-form").valid()) {
$("#my-form").submit();
}
});
This also seems to be a good solution if you have say textboxes with a plugin to make those textboxes into a calendar control. Only reason I say this is because I used Zebra Datepicker with an MVC form and it would submit an invalid form if focus was on the calendar date picker. Using the below code stops this.
I was having the same issue Yablargo was having in that it was saying that valid is not a function, so I came up with this:
For the onclick handler of the submit button, I put this:
onclick="return $(this).closest('form').checkValidity();"

Manually bind JQuery validation after Ajax request

I'm requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery's unobtrusive validators plug-in.
The client script is not however working and my theory is that its because the validation framework is only being triggered on page load which has long since passed by the time the MVC view has been loaded into the live box.
Thus how can I let the validation framework know that it has new form fields to fix up?
Cheers, Ian.
var $form = $("form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
You may take a look at the following blog post. And here's another one.
Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call
this.ViewContext.FormContext = new FormContext();
Reference
For some reason I had to combine bjan and dfortun's answers...
So I put this in my view:
#{
this.ViewContext.FormContext = new FormContext();
}
And this execute this after the ajax call finishes:
var form = $("#EnrollmentForm");
form.unbind();
form.data("validator", null);
$.validator.unobtrusive.parse(document);
form.validate(form.data("unobtrusiveValidation").options);
I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the
#Html.TextBoxFor
for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the
data_val_required
attribute, for example.
However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.
bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.
All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

Resources