Skip to content Skip to sidebar Skip to footer

Change Classes And Display Message When Form Is Submitted With Angular

I'm using ngMessages to display error messages with my form validation and this is working. Now my problem is when I submit the form I want to change the classes from being valid

Solution 1:

Update

I'm afraid that you can't do what you need directly, because if you change the conditional there are 2 states which will conflict with each other:

The user fills the form correctly and submits VS The user press Submit, then fills a field correctly

In the second case the field won't be show the valid-field green border.


What you should do is make a function which checks the valid fields, and execute it on the submit, then set a flag on true for a class global on your form which will override your current valid/invalid states

Here is the working solution

//Validate States$scope.validateSuccessSubmit = function(){
      if($scope.contactForm.nameField.$valid && 
        $scope.contactForm.emailField.$valid &&
          $scope.contactForm.$submitted) {
            $scope.formCompleted = true;
          }

    };

<!-- Form --><formnovalidatename="contactForm"ng-class="{'form-completed' : formCompleted}">

/*CSS*/.form-completedinput{
  border: 1px solid darkgray;
}

Previous incorrect answer:

Just add the !$submitted condition on the valid-field class

ng-class="{'invalid-field': contactForm.nameField.$touched || contactForm.$submitted, 
'valid-field': contactForm.nameField.$valid && !contactForm.$submitted}" 

//And 

ng-class="{'invalid-field': contactForm.emailField.$touched || contactForm.$submitted,
 'valid-field': contactForm.emailField.$valid  && !contactForm.$submitted}"

Solution 2:

Use the following code it will work fine but what you need to is write css class like:

    .initial
   {
     1px solid darkgray;  
   }   

and use the following html for ng-class of you input elements.

 ng-class="{'invalid-field': contactForm.nameField.$touched && !contactForm.nameField.$valid, 
 'valid-field': contactForm.nameField.$valid&& !contactForm.$submitted , 
   'initial':contactForm.nameField.$valid && contactForm.$submitted}" 

  ng-class="{'invalid-field': contactForm.emailField.$touched && !contactForm.emailField.$valid,
  'valid-field': contactForm.emailField.$valid && !contactForm.$submitted , 
   'initial':contactForm.emailField.$valid && contactForm.$submitted}"

And finally I for the "Your message has been sent!" message you need to write

     <div ng-messages="contactForm.$valid" ng-if="contactForm.$submitted && contactForm.$valid">

       <span class="sent">Your message has been sent!</span>

   </div>

Post a Comment for "Change Classes And Display Message When Form Is Submitted With Angular"