Forms in Angularjs. How i found love

I had to do it again. It would seem nothing terrible, I did it hundreds of times. But the feeling ... the feeling that all this is wrong, should not be like this and there should be another way, did not leave me. Then I did not know that soon I had a meeting that would forever change my world, open my eyes and fill my life with meaning. The meaning of getting up every morning, the meaning of doing what almost ceased to give me pleasure, the meaning of sharing this feeling with others.

River flows...

This story dates back to 1992, when the first version of the scripture was published , most of whose covenants determined the course of human development for many years to come. An attentive reader will certainly notice that in this manuscript there is no mention of several very important canons, without which not a single clergyman can do today.

Among them, one of the main heroines of my story. With the naked eye you can see that the original HTML, like a diamond that has not been cut, was formless. Naturally, this could not continue for a long time, and already on November 8, 1993, the first features of a new form appeared from the bowels of the jewelry workshop to the world , which subsequently got their rightful place on the tablets of the second coming.

And it would seem that harmony has come in the world. Now ordinary people could not only receive information, but also respond. And in the event that heresy is found in their words, the mysterious guard from Backend will always come to the rescue and with his righteous speeches will set the right path. But the calm has no place in this drama.

The whole history of mankind is the path to freedom. Freedom from slavery, from the oppression of kings, from the borders of their native lands. It is enough that for a thousand people living in humility, one freethinker is found, and then ships sail again, barricades are erected, Negroes run for president. So it was this time, people wanted freedom, freedom from the bonds of the server side. Freedom, which promised them the divine power of interfaces, savings on data transfer, the road to the golden city of Frontend.

Come to the point

But back to the main line of the story. What happened to the form? The shape began to change. With the development of the Frontend from a kind of pagan portal into the world of browser life, it became an element of its decoration, transferring its strength into the hands of the Javascript Church. Why did this happen, only Morgan Freeman knows, we will take a look at the facts. And the facts are such that only the Old Believers continued to check the form on the server side, and the Jesuits, who spit on the desire of mankind for perfection in the conditions of ignorance of the customer.

Your humble servant never related himself to either one or the other. A young rake, I lived and enjoyed life. Need validation? Yes please jQuery validation, yes, even I’ll write it myself. Over and over the same thing: email, password, name ... email, password, name ... email, password, date ... And like a spinning top in a safe, a thought arose in my head that was spinning and spinning endlessly. Now, when I had the task to write the processing of the form, I was overcome by the feeling that I was an Indonesian peasant who was forced to mop off the snow from the windshield of his moped for lack of wipers, which, according to common sense, should have been installed at the factory.

And here, of course, as a decent parishioner of the Church of the Holy Trinity , my joy knew no bounds when the miraculous attributes of the fifth reincarnation were sent to us. Once again, they gave me hope and faith that there, on the other side of the cable, there is someone and he hears my prayers. But, admittedly, the euphoria was short-lived. The lack of the possibility of stylization, control of the state of filling out the form still required each time to prescribe the logic that controls the presentation.

But once, in the circle of my sectarian friends, they brought me together with a beautiful maiden. She was young and was just beginning to go out. Her name was, if in the Russian manner, Angela . At first she seemed strange to me. Most of all, I was confused by the fact that she did not try to hide anything, but everything was in the forehead. It was wild for my upbringing . I don’t know if she attracted me with her manners or, perhaps, what influenced me was that I admiredher father , a serious authority in our circles. But I wanted to get to know Angela better, since she was available to the girl .

Well, don't pull

I will not go into all the details of our relationship, especially since I was not the first one with her . Angela’s language was capable of such incredible things that I wanted to know it deeper and deeper. But as I remember now, the day when I finally lost my head. This day she first showed me the form.


In general, it was indescribable. She, as if reading my thoughts, did everything that I could wish for. Do you want to set styles for pristine input and no? Ask, she swallows.

/*Целомудренная форма*/
/*Пользованная форма*/

It remains only to write code that will apply these styles. Here it is:

[ jsFiddle ]

If someone already has a
question, what about valid-invalid?

[ JsFiddle ]
/*Правильная форма*/
/*Плохая форма*/

In general, guys, chained. He began to court her. And then she, it must be said, revealed in full. I realized that setting styles was just fun for a first date. In fact, she could do something that others could not even dream of. Make a validation interface with custom messages without a single line of JavaScript? Made by:

[ jsFiddle ]
You break my heart

And here is a complete analogy with styles, that is, in the LovelyForm.LovelyEmail object, logical properties are defined that correspond to the styles given above:

(boolean) LovelyForm.LovelyEmail.$invalid;
(boolean) LovelyForm.LovelyEmail.$valid;
(boolean) LovelyForm.LovelyEmail.$dirty;
(boolean) LovelyForm.LovelyEmail.$pristine;

The juice itself is that directives are duplicated in Angular out of the box, duplicating HTML5 form validation attributes.

[ jsFiddle ]
Show me your numberOMG, so minOMG, too maxWhat?! Fucking buster!

Personally, I was delighted with this because the notorious HTML5 was lacking in such minimal flexibility.

Own validator

Well, and most importantly, with what ease Angela is ready to accept the validator that you created on the side into her bosom. To do this, just write the appropriate directive:

[ jsFiddle ]
app.directive('mimimi', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function(mimimi) {
                if (/mimimi/.test(mimimi)) {
                    ctrl.$setValidity('mimimi', true);
                    return mimimi.toUpperCase();
                } else {
                    ctrl.$setValidity('mimimi', false);
                    return undefined;

Mimimi, please{{mimimi}}

It often seems to me that the Angular developers sought to create a framework whose code would cause the same feelings in people who are familiar with programming, and not. Therefore, I will explain a little what is happening, especially since its essence is rather simple.

When using the ngModel directive, Angular creates an instance of a special NgModelController controller for it , which is basically responsible for all these validation properties: $ invalid, $ valid, $ pristine, $ dirty, $ error. Therefore, when writing a validator, we need to use a controller that belongs to ngModel, which we do:

require: "ngModel"

Now the link function, which is called upon any changes, will accept the NgModelController controller as the ctl parameter .

Next we turn to the array $ parsers object NgModelController , who consistently perform specified functions, transferring them to the contents of the input.

Perform a regular expression check. And if everything is ok, declare LovelyForm.LovelyMimimi. $ Error.mimimi valid ctrl. $ SetValidity ('mimimi', true). The value returned by the function will be passed to the parent $ scope, in our case, to the mimimi variable.


And finally, we want to process the data that the user has kindly provided to us. With Angular, this is also done at times:

[ jsFiddle ]

function formController($scope){

In fact, one of the two ngSubmit or ngClick directives is sufficient. The only difference is that the first you specify in the form tag, the second to input with the type = "submit" attribute. In this case, the specified function will be performed both when the button is clicked and when Enter is pressed after entering in one of the fields.

Of course, in order to prevent the appearance of native HTML5 validation messages, it is advisable to assign the novalidate attribute to the form. And in order to prevent the submit or click action when the form is filled out with errors, we use the ngDisabled directive. If ngDisabled is true, then submit will fail.


In general, why am I, men. Be careful. I lived my life, changed plugins for jQuery like gloves. But once he relaxed, stuck his nose in, but did not pull out in time. Now, Angelka and I will have children soon, one-page, so I can’t even look at jQuery now. But I think I'm not the only one here. Thank you for listening.

Also popular now: