javascripthtmlangularjsng-dialog

Validate form within ngDialog openConfirm before closing


I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.

Here is a simplified version of my code:

someFunction() {
    let newScope = $scope.$new();
    newScope.vm = vm;
    ngDialog.openConfirm({
        scope: newScope,
        template: 'componentDescription.html'
    })
}

And my html:

<form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

I would like for the Dialog to only be submitted if the form is valid.

I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.

Any ideas?

UPDATE: I've changed my html like so:

<form role="form" name="subForm" novalidate ng-submit="confirm(0)">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="submit">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.


Solution

  • You can manually decide whether to call $scope.confirm() or not,

    Pass validation then call $scope.confirm().

    Not Pass validation, don't call $scope.confirm().

    e.g.

    Template:

    <button type="button" ng-click="ok(0)">Submit</button>
    

    Controller:

    $scope.ok = function () {
        if(!validationHasPassed()){
            //errorMsg.push('xxx')
            return false;
        }
        $scope.confirm();
    };