SailsJs ajax-form validation - sails.js

Is there a way I can run a function on the built-in vue component "ajax-form" in SailsJs? I want it to run when the form is submitted and do some validation, but take place before the data is sent to the back end.

Ajax-form is super handy. And it's well supported by Sails.js
Here is an example of how you can set up your form:
<ajax-form action="createOneThing" :syncing.sync="syncing" :cloud-error.sync="cloudError"
:form-errors.sync="createThingFormErrors" :form-data="createThingFormData"
:form-rules="createThingFormRules" #submitted="submittedCreateThingForm($event)">
<label for="thing-name">Thing Name:</label>
<input class="form-control" :class="[createThingFormErrors.thingName ? 'is-invalid' : '']"
type="text" id="thing-name" v-model="createThingFormData.thingName">
<div class="invalid-feedback" v-if="createThingFormErrors.thingName">Make up a name for your thing.</div>
<ajax-button type="submit" :syncing="syncing">Delete</ajax-button>
</ajax-form>
Now you have to make sure you set your objects in your page script under data:
createThingFormData: {},
createThingFormErrors: {},
createThingFormRules: {
thingName: { required: true },
}
You can also check out this post for more usage info about Ajax
https://www.formget.com/form-validation-using-ajax/

Related

About the $dirty property and getting only modified fields in a form

I have a form with few fields and I'm trying to get modified fields only.
Here is what I got so far (simplified version) :
<form name="formTicket">
<div class="item title">
<label for="category-assignation"><?php echo T::_("Assignation :")?></label>
<textarea type="text" name="assignation" cols="50" rows="4" id="category-assignation" data-ng-model="ticket.assignation"></textarea>
</div>
<div class="item title">
<input id="save" type="submit" value="Save" data-ng-click="saveTicketInfo()" />
</div>
</form>
In my controller.js, I have :
$scope.saveTicketInfo = function() {
console.info($scope.ticket);
console.info($scope.formTicket);
//Query to my service to save the data
Category.saveInfo.query({data: $scope.ticket});
};
Prior to AngularJs, I would save my fields in an array at the loading of my form and compare their values with the new values posted. I could still do this but I'm looking for an AngularJs approach.
I've been trying to use the $dirty property of each field and only send to my services those with "true" value but this behavior is not suitable for me : if the defaut value for my field is "test" and the user modify the input to "test2" and modify it back to "test" and post it, $dirty will be true (even if the value has not really changed).
Is there any convenient and optimal way to achieve what I want ?
Thank you for your time.

How to edit data when combining angularjs and mongodb

I'm a beginner in the AngularJs and MongoDb world (i started learning today!!)
Actually i'm trying to do something very basic : Display a list of record, with an add button and a edit link with each record.
I'm using this lib https://github.com/pkozlowski-opensource/angularjs-mongolab to connect to mongoweb.
Actually my data is displayed, when i try to add a record it works, but the problem is when i try to display the edit form!
Here is my index.html file, in which i display the data with a form to add a record and with the edit links :
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
<form ng-submit="addTeam()">
<input type="text" ng-model="team.name" size="30" placeholder="add new team here">
<input type="text" ng-model="team.description" size="30" placeholder="add new team here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
And here is my edit.html code, which displays an edit form :
<div ng-controller="EditCtrl">
<form ng-submit="editTeam()">
<input type="text" name="name" ng-model="team.name" size="30" placeholder="edit team here">
<input type="text" name="description" ng-model="team.description" size="30" placeholder="edit team here">
<input class="btn-primary" type="submit" value="validate edit">
</form>
</div>
And finally my js code:
var app = angular.module('app', ['mongolabResource']);
app.constant('API_KEY', '____________________________');
app.constant('DB_NAME', 'groups');
app.factory('Teams', function ($mongolabResource) {
return $mongolabResource('teams');
});
app.controller('AppCtrl', function ($scope, Teams) {
$scope.teams = Teams.query();
$scope.addTeam = function() {
varteam = {
name: $scope.team.name,
description: $scope.team.description
};
$scope.teams.push(varteam);
Teams.save($scope.team);
$scope.team.name = '';
$scope.team.description = '';
};
});
app.controller('EditCtrl', function ($scope, Teams) {
//????????
});
My AppCtrl works perfecty, it displays the data w add records perfectly.
Now i want to add the js code for the edit, but i don't even know form where to start ? how do i a get the id parameter in the url ? how do i tell the view to fill out the form fields from the values from the database ? And finally how do i update the databse.
I know that i asked a lot of question but i'm really lost! thank you
There are of course many possible solutions.
One solution is to use angularjs routing. See http://docs.angularjs.org/tutorial/step_07 for a tutorial.
Basically replace your ul list with something like:
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
Then you can create a route that responde to your url:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detail.html',
controller: 'TeamDetailCtrl'
}).
otherwise({
redirectTo: '/teams'
});
}]);
In this way from the detail controller (that will replace your EditCtrl) you can access the id parameter using: $routeParams.teamId
Anyway I suggest to study well all the tutorials for a better overview.

Meteor: how to accept user input in a set of form fields

New to Meteor. I have a form with several fields
<template name="addcityform">
<form name="addcity">
<input name="city" class="city" type="text">
<input name="population" class="population" type="text">
<input type="Submit" value="Add City">
</form>
</template>
I just want to insert the fields into the database, but I'm stumped on how to do it. Here's what I currently have after several attempts:
Template.addcityform.events({
'submit .addcity' : function(evt, template) {
Cities.insert({
city: template.find('input.city').value,
population: template.find('input.population').value
});
}
});
// this gives: Uncaught TypeError: Cannot read property 'value' of null
I saw some examples that use Session.set and document.getElementById, but that seems clumsy to me due to the potential for namespace conflicts. I'd like to do this the 'right way' so that it's extensible later, for example, I could put multiple instances of the form onto the page and they should be independent of each other. What is the 'right way' to do this?
You lack an event.preventDefault() in the "submit form" handler, or else the page will reload and ruin the single-page app experience of Meteor.
I would do something like :
<template name="addcityform">
<form>
<input name="city" class="city" type="text">
<input name="population" class="population" type="text">
<button type="submit">Add City</button>
</form>
</template>
Template.addcityform.events({
"submit form": function(event, template) {
event.preventDefault();
Cities.insert({
city: template.find(".city").value,
population: template.find(".population").value
});
}
});
What's cool about Meteor templates is that css selectors used within them are local to the current template, meaning that "submit form" will always refer to "submit event of the form element in enclosing template", given that you only have one form in the template.
The same applies to template instances .find method : it will return an element matching the css selector within the template or its sub-templates.
This allows you to have multiple instances of your addcityform that will be independent from each other.

Angular JS: sending form field data in a PUT request (like POST does)

I'm trying to write a client that does all four REST verbs (GET/POST/PUT/DELETE) and have gotten all but the PUT done. The REST/CRUD API I'm working from wants to update an entry by calling PUT /realmen/ID-string and including the key-value pairs as JSON. For a POST this seems to work "automatically", but not for a PUT.
My HTML looks like:
<div id="list">
<form novalidate class="edit-form">
<p>Title <input ng-model="realmen.title" type="text" value="{{realmen.title}}" /></p>
<p>Real Men <input ng-model="realmen.realmen" type="text" value="{{realmen.realmen}}" /> </p>
<p>Real Role-Players <input ng-model="realmen.realroleplayers" type="text" value="realmen.realroleplayers}}" /></p>
<p>Loonies <input ng-model="realmen.loonies" type="text" value="{{realmen.loonies}}" /></p>
<p>Munchkins <input ng-model="realmen.munchkins" type="text" value="{{realmen.munchkins}}" /></p>
<input ng-model="realmen.entryId" type="hidden" value="{{entryId}}"/>
<button ng-click="change()">UPDATE ({{entryId}})"</button></p>
</form>
</div>
My controller looks like:
$scope.realmen = RealMen.get({entryId: $routeParams.entryId}, function() {
$scope.master = angular.copy($scope.realmen); // For resetting the form
});
$scope.change = function() {
console.log($scope.realmen);
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
And finally, my services look like:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
var RealMen = $resource(
'http://localhost\\:3000/realmen/:entryId',
{},
{
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method: 'PUT', params:{entryId:'#entryId'}},
remove: {method:'DELETE'}
});
return RealMen;
});
The PUT is getting called with the correct id value in the URL, but the Request Payload only contains the entryId, so the backend API gets no expected keys and values and essentially blanks out the record in the database.
The console.log($scope.realmen) does show the form fields, along with a lot of extra data. I tried calling RealMen.update($scope.realmen, ...) (similarly to calling .save()), but all those extra fields are tacked on as query string parameters to the URL in a spectacularly ugly fashion.
Because your $scope.realmen is a resource instance, instead of using RealMen.update, you can just call $scope.realmen.$update() (note that there is a "$"). The instance action method will take care of sending the data for you.

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});