Kindzoku
Kindzoku

Reputation: 1420

Angular: better form validation solution

Need advice about form validation.

I have control structure like so:

<form name="myForm">
    <control-wrap>
        <label isRequired="myForm.field1">Some text here</label>
        <custom-control name="field1" 
                  ng-required="true"
                  ng-something-else="any"
                  ng-model="modelForm.field1"></custom-control>
        <info>Some data after control</info>
        <error-list field="myForm.field1"></error-list>
    </control-wrap>

    <control-wrap>
        <label isRequired="myForm.field2">Some text here</label>
        <custom-control name="field2" 
                  ng-required="true"
                  ng-something-else="any"
                  ng-model="modelForm.field2"></custom-control>
        <info>Some data after control</info>
        <error-list field="myForm.field2"></error-list>
    </control-wrap>

    <control-wrap>
        <label isRequired="myForm.field3">Some text here</label>
        <custom-control name="field3" 
                  ng-required="true"
                  ng-something-else="any"
                  ng-model="modelForm.field3"></custom-control>
        <info>Some data after control</info>
        <error-list field="myForm.field3"></error-list>
    </control-wrap>
</form>

And this is completely AWFUL, unDRY and I guess I'm doing something very wrong.

I want to stop using field names, but I don't know how to pass ngModel to the sibling the proper way (now I'm forced to pass ngModel via attributes to isRequired and error-list).

Best solution for me ofc is to require: '^ngModel' from isRequired and error-list.

Any advice will be very appreciated.

P.S. there is no way for me to store fields in json object, there is a lot of logic between fields and different tweaks on labels and hints.

Upvotes: 1

Views: 166

Answers (1)

Kindzoku
Kindzoku

Reputation: 1420

Well, I came to this solution: https://plnkr.co/edit/mPXpEaZs2uWZb3WRkmgp?p=preview

Maybe it's not the best solution, but I don't need names anymore.

The main idea is to set model reference to parent container and watch this reference from other children.

So in the end I have:

    <control-wrap>
        <label link-required>Field1 label:</label>
        <input link-to-wrap ng-model="mc.field1" 
            type="text" 
            ng-required="true" 
            ng-minlength="5" 
            ng-maxlength="10" />
        <errors-list></errors-list>
    </control-wrap>

UPDATE

Some more thoughts about storing validation rules with model:

https://plnkr.co/edit/6ZVv685oSRDt7ELBKb9z?p=preview

New directive my-rules and extended data in controller.js

Upvotes: 1

Related Questions