Field and Form Validation with ember.js - forms

I've integrated Boronine's excellent field validation code for ember.js from jsfiddle. While that is wonderful, I still need to perform form level validation, to ensure that when the user submits the form, everything is okay.
What's the best way to do that? Is there a way that I can mark a field as having been validated, so that the form handler can simply walk the fields to see what has been validated or not?
MP.SignUpFormView = Em.View.extend({
submitLogin:function (event) {
// walk through object fields to perform validation here, but how?!
}
});
Edit:
For clarity, I am using Handlebars and binding, not trying to walk DOM objects or the like.

The pattern you're trying to use makes sense in applications that follow a document-scripting pattern, which Ember does not. You can force this work, but you'll find each next step in the application will get harder and harder.
In Ember display is backed by data objects so form fields in an Ember application are bound to a property on some object and as changes are made, the values are updated immediately. You don't even really need a <form> except maybe for styling.
When a user wants to take some action on this object (like persisting it to a server) the application's current state will answer the question "what happens when a user wants to take this action right now?" A user clicking a button here doesn't mean "now serialize the data in the form and do something" it means "I'm done changing the properties of this object and would like to do something else in the application now."
Your handlebars template would look something like this:
{{view Ember.Textfield valueBinding="name"}}
{{view Ember.Textfield valueBinding="age"}}
<button {{action save content}}>Save</button>
And a possible state in your application where this can be handled
Ember.Route.extend({
save: function(router, event){
if (event.context.validate()){
router.transitionTo('someNewState')
}
}
})

Related

AEM: Display an Alert box after server side validation

I have a form in AEM. When the submit button is clicked control goes to forward.jsp. I have done some validations in forward.jsp and would like to generate on alert on the page once the validation is failed. How can I pass the alert to the page?
if(condition){
// validation success
} else{
// code for alert
}
FormsHelper.redirectToReferrer(slingRequest, slingResponse);
If you want to do the validation server-side, but show an alert client-side, I recommend you use JavaScript to make an AJAX call. You could change your submit button so that when it is clicked, it fires an AJAX call instead of submitting a form. See http://api.jquery.com/jquery.ajax/ for a description of how this could be done using jQuery, but other options would also work for making the AJAX request.
In the response to that AJAX request you can put whetever you need. It can be a status code, a string of JSON, or a blurb of HTML. You then would write client-side JavaScript to handle the response and do whatever is appropriate based on the given response--such as show an alert on the page.
An example of this sort of approach if seen at http://michaelsoriano.com/how-to-ajax-validate-forms/
This topic is more complicated that you might think. Basically you can see sample implementation in the foundation components such as /libs/foundation/components/form/text/text.jsp. They all use the com.day.cq.wcm.foundation.forms.LayoutHelper#printErrors method to check if they are errors on field. This is happening over the com.day.cq.wcm.foundation.forms.ValidationInfo class which is set as request attribute in order to transfer the field state between the different classes. You can check also the com.day.cq.wcm.foundation.forms.FieldHelper class which performs actually the validation. Putting some sort of logic in the forward.jsp is the wrong ways

Grails: calling an action that uses withForm

I have a situation in which I need to reuse an action that has its functionality wrapped in a withForm closure.
Everything works well when submitting the form but when I try to reuse that action in another way I get redirect errors from my browser. Specifically, I need to redirect another action to it, possibly call it with chain, and I also want to call it from a hyperlink.
I'd really like to avoid creating a redundant action or having the invalidToken closure execute the same code. I've tried to find some more details about how withForm works and find out what happens if no token is passed to the closure but the Googles have let me down.
Is this possible? Am I trying to make it do something it can't?
More info:
I have a user edit controller action. It is wrapped with the withForm closure. There are three different cases in which I need to call this controller to render the user edit page:
An admin enters the user's id into an input and clicks the form
submit button (this form uses useToken). This needs to be secured
and protected from duplicate form submission.
An admin selects a user to edit from a list of employees by clicking
on the user's name (a hyperlink). Its possible I could turn this into a form submission with useToken and do some CSS styling to make it look like a link.
An admin creates a new user. When the user is successfully created
the create controller redirects (or uses chain) to the edit
controller. I can't find a work around for this, except to create a redundant controller.
If your code is used in more than one place a controller action isn't the best place to put it. I suggest you to move that piece of code to a service and call it from both actions.
Here is my solution. If anyone has some insight into other methods of solving this please contribute. I'm sure I'm not the only one that has had this problem.
The answer is due, in large part to #Sergio's response. It was far more simple than what I was thinking it would be. I created my edit action without withFormthen call it from another action that wraps the edit action in the withForm.
def editWT(Long uid, Long pid){
withForm{
edit(uid, pid)
}
}
def edit(Long uid, Long pid){
// Do lots of stuff to prep the data for rendering the view
}
This answer isn't innovative or ground-breaking but it works. I hope this helps someone else.

Google Chrome Inspect Element Issue With Hidden ID's

I am not 100% sure if this is as big an issue has I seem to think it is right now but I think I may of found an issue or at else an hole within the Inspect Element viewer within Chrome.
I was using (I have now changed my settings) hidden ID's to set a number of defaults, one was users levels, another was to make the user active by default.
However when I view these ID's within the inspect Element view and then changed the values, submitting the form would submit the NEW value to the server and not the value I had given it.
For Example:
I had something like the following within my code,
<input type="hidden" name="data[user][level][id]" value="1" id="MyID">
I then changed it within the Inspect view to,
<input type="hidden" name="data[user][level][id]" value="2" id="MyID">
Then I submitted the form and was surprised that the NEW value was submitted, I was always under the inpresion that hidden ID's where not changeable and the browser should only submit the default values held within.
I have now changed this to letting the database default to a basic user and then I can change the users setting has I want to. But in some cases this may not be an option, so I was hoping for an answer or some feedback about how to make this more safe.
Am I just a bit slow, are there better methods (different ones) to passing 'hidden' data from forms to the server?
I was thinking about maybe using JQuery to add the needed hidden fields to the forms once the user had selected / submitted the form, but i am not sure if this is 100% safe or even if its a good idea.
Any ideas / feedback are very welcome.....
Many Thanks,
Glenn.
I had the same problem passing the database data into a modal,the solution i know is to use jquery ajax to get the informations from the database requesting a file,adding them into variables and compare the variables
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
I used this code sample to do it.
Of course there are a few modifications to be done depending on your script
I found a better way of doing this, at lest in CakePHP. The CakePHP framework has inbuilt security calls. These in-built functions when added give you all sorts of stuff but the main reason I used them was to stop this sort of form tampering.
I am not 100% sure how it does this, but it adds a token to all forms and it checks to see if the form being submitted is right? Again not sure how the token works.
But here is the code I used ::
public function beforeFilter() {
$this->Auth->allow('index', 'SystemAccess');
$this->Security->blackHoleCallback = 'blackhole';
}
public function blackhole($type) {
$this->Auth->logout();
$this->Session->setFlash('Sorry a security issue has been detected, please try again or contact us for support.', 'default', array(), 'bad');
$this->redirect($this->Auth->redirect('/'));
}
Now I will add that the call the Auth logout I added to this for extra added security, as the user maybe have logged in on a system and it just not be them that is trying to do things that they should not.
Hope that helps others out!
But this is only a fix for when CakePHP is in use. I would take it that other frameworks would have their options but if your only using basic HTML? or a CMS like Drupal again there might be in built security.
Many Thanks
Glenn.
The only safe and best solution that I found for this issue is to check on the server side whether the user_id sent with the form is the same user_id logged in with or not.
Although using jquery is good idea, but, did not work with my case as am using data: $(this).serialize(),
However here's my code on the server side (Note, am using Laravel 5.4, but am sure it won't matter with your case)
if ($request->user_id != Auth::user()->id)
return json_encode("F**K YOU ! Don't Play Smart -_- !");
else
raw_material_category::create($request->all());
Hope this helped ;)

Yii - How to call external javascript on every CActiveForm validation?

I would like to make a "preview container" for form values in Yii. (so every time the user finishes entering data, the "preview container" below the form will display them, to let the user knows how the item actually looks like).
To achieve this, the only way is to call a Javascript function to update the "preview container" (using jQuery). The CActiveForm is:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'item-form',
'enableAjaxValidation'=>true,
));
?>
How do we modify it to call a javascript function each time the fields are validated?
(Note: whenever we switch between the input fields, the fields are validated dues to enableAjaxValidation=>true)
Thanks in advanced.
With jQuery you can define your own listener functions for the fields you want to update, which is probably going to be cleaner than trying to hook into the validation functions.You could monitor onchange or blur or whatever is most appropriate to your data.
The js can be loaded via Yii's registerScript function or, again, whatever is most appropriate for your app. A listener function would normally be loaded on DOM ready, i.e., with the POS_READY attribute for registerScript.
You can search the tutorials as well as this basic tutorial for more info.

MVC: Client Validation Fails, but data is still posted

As above, I'm implemented the client side validation no problem, and it pops up the relevant messages as required. However, the submit button still appears to submit the form even though the form is not in a valid state.
The controller method throws it out immediately, because ModelState is not valid, but is there a flag/property I can check client side to prevent the post from happening at all?
UPDATE:
The problem appears to be because the form is submitted asynchronously using a jquery post, hence my javascript method is posting the data regardless of the validation state. So what I'm looking for is, before I do that post, to do something along the lines of if( [Property/Method which indicates MVC Model State] == false ) return false;, however, I'm struggling to find such a method or property.
I've considered implementing a check function which identifies whether the 'input-validation-error' class is applied to any of my form fields. With JQuery, it's pretty simple, but it doesn't sit to well with me. Does anyone have any opinions on doing this?
On the one hand, it seems a bit of a hack because I'm effectively iterating through the form after it's been validated to see if it's actually valid. On the other hand, I'm not sure how the MVC JS would identify the modelstate if there were multiple forms on the same page, whereas if I was to do it myself, I could identify 'for the post of this form, I'm interested in these fields'.