0

I'm thinking of a good way to implement ng-required. Let's say I have a bunch of inputs with ng-required in my app.

<input type="text" id="one" />
<input type="date" id="two" />
<input type="radio" id="three" />
<input type="checkbox" id="four" />

I would like to do something in a controller, where I could pass an array of required fields. I'm thinking that if I made an array of elements such as:

var myEl = angular.element( document.querySelector( '#some-id' ) );

and some how set the required property that way.

I write a directive which would decide from an array if the field is required, if it does not exist in the array, it's not required if it does, it's required.

Ultimately, I would like to have an array that allows passing of fields in such a way:

var reqArray = ('#id', ('#id1' || 'id2')) etc. 

Works the same as conditional logic operators:

#id is required

#id1 || #id2 is required, but not both.

Not sure where to begin, or if it's feasible in Angular.

This would make it easier to modify required fields in large applications without having to modify the actual html.

1 Answer 1

1

It can be done, but angular already provides its own ways to validate forms. Some brief details:

  • The form tag must have a novalidate attribute in order to prevent HTML5 validation. <form name="myForm" novalidate>

  • With that, now angular can take charge of the validation by adding a "required" attribute to your inputs <input ng-model="myModel" type="text" required>

  • By this point, angular has taken control of your validation, it can also validate other HTML5 attributes like pattern. <input pattern="[0-9][A-Z]{3}" type="text" title="Single digit followed by three uppercase letters."/>

I suggest you take look at this official guide (also take a look at the directives guide on that same site, I wanted to link it but I don't yet have the rep).

That being said, what you are trying to accomplish is also possible, but rather redundant since you would have to add an attribute to your inputs anyway (the directive, and angular is able to validate already) and also require ngModel in the directive.

I made this plunkr to show you how to do it, but take notice of the extra work needed in order to validate something that angular already does natively, I'd leave this kind of work for expanding on validations, like comparing items or models.

Also, querying a selector directly like in your suggestion is not considered "the angular way". A better way would be to add the directive to your form element and access the element through the 'element' parameter in the directive.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.