What *is* the ngModel.$validators pipeline? - javascript

While performing some basic research on custom client-side validation in Angular.js, I was reading the ngModel.NgModelController documentation, and found the following cryptic line:
$setValidity(validationErrorKey, isValid);
Change the validity state, and notifies the form.
This method can be called within $parsers/$formatters. However, if possible, please use the ngModel.$validators pipeline which is designed to call this method automatically.
A couple of hours and many Google (and StackOverflow!) searches later, I have found nothing about this ngModel.$validators pipeline anywhere. All custom validation examples use the $parsers/$formatters setup as below:
link: function (scope, elem, attr, ctrl) {
// Other necessary logic...
ctrl.$parsers.push(function () {
// Validation logic
ctrl.$setValidity('validation-type', true);
});
ctrl.$formatters.push(function () {
// Validation logic
ctrl.$setValidity('validation-type', true);
});
},
Question: The Angular documentation states that the above code is not the best practice, and that this mythical ngModel.$validators pipline is the correct way to go. I have failed to find any information on this better practice. How does one use ngModel.$validators to correctly implement this custom clientside validation?

$validators are new to Angular 1.3. This blog post gives a good explanation on how to use them: http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#the-validators-pipeline
The basic idea is that you add a function onto ngModel.$validators that returns a boolean specifying whether the model is valid.
Then you can refrence that validator in your HTML the same way you would reference any built in validators. e.g.
<div ng-if="myForm.myField.$error.myValidator">
some error message here
</div>

Related

Custom Unobtrusive Validation Method Not Firing as Per Documentation

I've been attempting to implement a ASP.NET MVC custom validation method. Tutorials I've used such as codeproject explain that you add data-val-customname to the element. Then jQuery.validate.unobtrusive.js then uses the third segment of the attribute
data-val-<customname>
as the name of the rule, as shown below.
$.validator.addMethod('customname', function(value, element, param) {
//... return true or false
});
However I just can't get the customname method to fire. By playing around I have been able to get the below code to work, but according to all the sources I've read Unobtrusive validation should not work like this.
$.validator.addMethod('data-val-customname', function(value, element, param) {
//... return true or false
});
I've posted an example of both methods
jsfiddle example
Any help would be much appreciated
I've updated my question hopefully to make clearer.
I have finally found got there in the end, but still feels like too much hard work and therefore I've probably got something wrong. Initial I was scuppered by a bug in Chrome Canary 62 which refused to allow the adding of a custom method.
My next issue was having to load jQuery, jQuery.validate and jQuery.validate.unobtrusive in the markup and then isolate javascript implementation in a ES6 class. I didn't want to add my adaptors before $().ready() because of my class structure and loading of the app file independent of jQuery. So I had to force $.validator.unobtrusive.parse(document);.
Despite this I was still having issues and finally debugged the source code and found that an existing validator information that is attached to the form was not merging with the updated parsed rules, and essentially ignoring any new adaptors added.
My final work around and admit feels like I've done too much, was to destroy the initial validation information before my forced re-parse.
Here is the working jsfiddle demo
Here is some simplified code
onJQueryReady() {
let formValidator = $.data(document.querySelector('form'), "validator" );
formValidator.destroy();
$.validator.unobtrusive.adapters.add("telephone", [], function (options) {
options.rules['telephone'] = {};
options.messages['telephone'] = options.message;
});
$.validator.unobtrusive.parse(document);
$.validator.addMethod("telephone", this.handleValidateTelephoneNumber);
}

how validation works in mongoose

I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html
It is said that validation occurs before saving document in the database.
And to turn this feature off we have to set option: validateBeforeSave to false.
However I have another decent Node.js tutorial example where they just use .validate as follows:
var course = new Course({});
course.validate(function(err) {
assert.ok(err);
assert.equal(err.errors['title'].kind, 'required');
course.title = 'Introduction to Computer Science';
assert.equal(course.title, 'Introduction to Computer Science');
var s = '0123456789';
course.title = '';
while (course.title.length < 150) {
course.title += s;
}
course.validate(function(err) {
assert.ok(err);
assert.equal(err.errors['title'].kind, 'maxlength');
++succeeded;
done();
});
});
I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?
validateBeforeSave, as the name implies, validates the mongoose object before persisting it to database. This is a schema level check, which, if not set to false, will validate every document. It includes both built-in (like a Number cannot contain string or a required field should exist etc.) and custom defined validations.
validate does the same, only it has no concern with saving the document afterwards. It's the method on the object which you invoke, like course.validate(callback), and get to know if the object is valid or not through err in the callback.
Both are doing one and the same thing but at different times and different level. Also, both are not mutually exclusive, so one does not need to be set off for other to work.
As for the use case of validate, unit testing is one example. You may want to test your validators without the trouble of mocking save or setting up a test database. I believe the example is trying to do something like that, though not in a structured way.
As you said mongoose is fireing up validation before save operation, but there are some cases when you want to validate document schema without save. For this you can use validate method directly.
Your example from tutorial show us piece of code representing unit tests. So for example we can check methods which generate some model to save without saving him.
Also validate method could help when you have complicated action flow with many saves and dependencies. For example you want to save user dashboard model with proper structure but firstly you saving user profile. With validate method and for instance wrong dashboard structure you can check request and throw exception before saving user profile.
In the example code, they are using Async Custom Validator which you would understand better if you check this: http://mongoosejs.com/docs/validation.html#built-in-validators
They are used when standard validation is not enough and this is purely my observation that they are usually used in testing along with some testing framework and assetion library.

Use directive as value for ng-if?

In my application, I need to be able to easily determine whether a user is authenticated within my HTML and in all templates.
My first thought on how to do this was to create a "global" controller and apply it to which simply set $scope.isAuthenticated = $auth.isAuthenticated.
However, after doing some reading, I discovered that this wasn't considered good practice. Instead, I created a directive, which would just return $auth.isAuthenticated().
angular.module('HordeWebClient')
.directive('isAuthenticated', function($auth) {
return $auth.isAuthenticated();
});
And then in my templates, I figured I could just use .... This doesn't work, the element isn't rendered regardless of the state of $auth.isAuthenticated.
The Safari error console doesn't show any problems, so I'm stuck on where to start in fixing this. Any pointers would be greatly appreciated.
In my opinion you should use .run on your main module.
angular.module('app').run(function(){
if(!isAuthenticated){
redirectToLoginView();
}
});
More: https://docs.angularjs.org/guide/module

Best way to handle more complex validation logic (required fields, etc.) on Backbone Model/View?

While Backbone's built-in validate() method on Models works fairly well for very simplistic cases, it quickly begins to fall apart when working on more complex validation logic, such as required fields. On the Model, here's how I'd typically handle validation of an attribute:
validate: function (attrs) {
var invalid = [],
dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/,
timeRegex = /^(\d{2}):(\d{2})$/,
isoDateTimeRegex = /^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{2}):(\d{2}):(\d{2})$/;
if (_.has(attrs, "chosenScheduleDate") && !dateRegex.test(attrs.chosenScheduleDate)) {
invalid.push("chosenScheduleDate");
}
// ...some more validation rules
if (invalid.length > 0) {
return invalid;
}
},
And then, within the View, filter through invalid attributes using the new-ish invalid event:
modelEvents: {
"invalid": "invalidateAttributes"
},
// ...other code
invalidateAttributes: function (model, error) {
if (_.contains(error, "chosenScheduleDate")) {
this.unsetModelAttributes("chosenScheduleDate", "chosenScheduleOpenTime", "scheduleOpenTime");
this.statusNotification.show.call(this, localizedText.displayText.theSelectedDateIsInvalid, "error");
this.ui.chosenScheduleDateInput.addClass("text-input--error");
}
},
This can result in an invalidateAttributes method that's quite long, especially if I'm validating 6+ Model attributes. Additionally, this doesn't take into consideration the concept of required fields, which I've handled by doing disagreeable has() checks:
if (this.model.has("scheduleOpenTime")) {
$.when(this.parent.saveAppointment.call(this))
.done(function () {
// set a new attribute on the model that represents the successfully-persisted datetime value
that.model.set("savedScheduleOpenTime", that.model.get("scheduleOpenTime"));
that.renderAppointmentForm();
});
}
And then would have to unset() attributes when they're invalid during an attempted set, effectively only allowing valid attributes to exist at all on the Model at any given time.
Is there a better, more elegant way to handle more complex validation, including required fields, on Backbone Models? Would really prefer a simplistic approach that doesn't utilize a heavyweight solution like the Backbone.Validation plugin or whatnot. Would love to see what kinds of patterns others are using.
Addy Osmani's Backbone Fundamentals book has a great section about model property validation. Using the Backbone.Validation plugin would have been my first suggestion since it handles required fields pretty nicely, but you explicitly mentioned wanting to avoid that. Addy's discussion of the topic touches on some alternatives including the Backbone.validateAll plugin, or focusing on validating forms instead of models.

How to remove the "name" param in for fields in ExtJS 4

I am integrating a payment provider into a ExtJS websites.
Basically, a form needs to be created and the form fields is send to the payment provider using Ajax.
The problem is that the payment provider does not allow that the form fields has a "name" param assigned to the "" tag. They do a manual check of the implementation and makes sure it is not there.
I assume it is a counter-mesasure for when the visitor has Ajax dissabled and the form gets submitted to my server instead, revealing the credit card. I know it does not make any sense with ExtJS, as it would not work without Javascript turned on, but non-the-less, that is the rule from the payment provider.
So, how can I force ExtJS to not put a "name" param in the form field? I have tried putting "name: ''" into the fields, but that gets ignored.
Do I use the template-system in ExtJS to solve this?
So Eric is perfectly right that it can be done much easier then modifying the whole template but non the less I would use a plugin for such a special case. I made a quick one:
Ext.define('Ext.form.field.plugin.NoNameAttribute', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.nonameattribute',
init: function(cmp) {
Ext.Function.interceptAfterCust(cmp, "getSubTplData", function(data){
delete data['name'];
return data;
});
}
});
Note the used method interceptAfterCust is a custom one of mine that modify the existing one by handing the result of the original to the intercepting one as argument. It is also using the given original object (which can be threaten as a scope) as scope for the original method. The easiest would be to add these method to Ext.Function
Ext.Function.interceptAfterCust = function(object, methodName, fn, scope) {
var method = object[methodName] || Ext.emptyFn;
return (object[methodName] = function() {
return fn.call(scope || this, method.apply(object, arguments));
});
}
Here is a working JSFiddle where the first field will not have a name attribute on the dom even if it exist in the component.
There's a surprisingly simple solution to this. I tested it with Ext.form.field.Text and Ext.form.field.ComboBox and it works well, but I don't know if it works for all form fields or if there are any negative side-effects. Use with caution.
Ext.define('Override.form.field.Base', {
override: 'Ext.form.field.Base',
getSubTplData: function(){
var data = this.callParent(arguments);
delete data.name;
return data;
}
});
Basically, it removes the auto-generated name from the render data before passing it along. The best part is that no private methods are involved so this should be a stable solution.
I prefer this in the field config options:
submitValue: false
Available since ExtJS 3.4

Categories

Resources