简体   繁体   中英

myForm.$valid returns true even though required feld is empty

I have a form myForm with some input fields.

What am I trying to implement: Each field is required only if at least one of the others input fields is not empty.

How I do it: I set ng-required="ctrl.isAtLeasOneFieldSet()" on each field. This function check to see if any field is set. Until here it works. If I set a field it returns true and if no field is set it returns false . I see it also in the "developer-console-inspector" in Firefox, required changes between true and false when I set and unset a value in one of the input fields.

What doesn't works: I habe a submit function in my controller:

function submitForm(valid) {
   if(!valid) {
      return;
   }
}

And on the form ng-submit="ctrl.submitForm(ctrl.myForm.$valid)" . Even though the ng-required is set to true and the input field is not set, the valid in submitForm returns true . I have used this technique thousand times with ng-required="someValue" but not with a functionl like now and it works fine. I think there is a problem when I set ng-required with ctrl.isAtLeasOneFieldSet() . It looks as the form will not get the update to required .

Here a simulation:

index.html - form

<form name="ctrl.myForm" class="form-horizontal" role="form" data-ng-submit="ctrl.submitForm(ctrl.myForm.$valid)" novalidate>
        <input name="name"
            data-ng-model="data.name"
            data-ng-required="{{ctrl.isAtLeasOneFieldSet()}}"
        />
        <input name="surname"
            data-ng-model="data.surname"
            data-ng-required="{{ctrl.isAtLeasOneFieldSet()}}"
        />
        <!---->
</form>

index.js - submitForm()

function submitForm(valid) {
    if(!valid) {
        return;
    }

    // Do something else
}

I found the problem in this case. Though I am not sure what is the difference.

right: data-ng-required="ctrl.isAtLeasOneFieldSet()"

wrong: data-ng-required="{{ctrl.isAtLeasOneFieldSet()}}"

If someone knows why it behaves like that and what exactly happens in each case, please write the answer here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM