Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
Programmatically set all form fields to ng-touched on form submission

HTML:

<div class="form-group" 
     ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }">
  <label for="firstName" 
         class="control-label">
         First Name
  </label>
  <input type="text" 
         name="firstName" 
         id="firstName" 
         ng-model="editableUser.firstName" 
         class="form-control" 
         required>
  <span class="help-block" 
        ng-show="form.firstName.$error.required && form.firstName.$touched">
        First Name is required
  </span>
</div>

<input type="submit" 
       ng-click="submit()" 
       value="Submit" 
       class="btn btn-default">

I'm trying to get my the 'has-error' class to kick in for invalid fields when a user clicks submit.

I would think you could do something like this:

$scope.submit = function () {
  if ($scope.form.$invalid) {
    angular.forEach($scope.form.$invalid, function(field) {
      field.$setTouched();
    });
    alert("Form is invalid.");
  }
};

But there is no $setTouched method in https://docs.angularjs.org/api/ng/type/form.FormController

EDIT: Realize $setTouched does exist, it's in https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

if ($scope.form.$invalid) {
    angular.forEach($scope.form.$error, function (field) {
        angular.forEach(field, function(errorField){
            errorField.$setTouched();
        })
    });
    alert("Form is invalid.");
}

plunker: http://plnkr.co/edit/XmvoTkIQ0yvFukrVSz11

over 4 years ago · Santiago Trujillo Relatório

0

Try the recently added $submitted

<input type="text" 
     name="firstName" 
     id="firstName" 
     ng-model="editableUser.firstName" 
     class="form-control" 
     required>
   <span class="help-block" 
    ng-show="form.firstName.$error.required && (form.firstName.$touched || form.$submitted">
    First Name is required

over 4 years ago · Santiago Trujillo Relatório

0

Extending on Alexey's answer, you can add new method to FormController that will do the same, so there's no need to copy code from one submit function to another:

// config.js
export default function config($provide) {
    $provide.decorator('formDirective', $delegate => {
        const fn = $delegate[0].controller.prototype
        if (!('$setTouched' in fn)) fn.$setTouched = function() {
            if (this.$invalid) {
                Object.values(this.$error).forEach(controls => {
                    controls.forEach(control => control.$setTouched())
                })
            }
        }
        return $delegate
    })
}
// controller.js
$scope.submit = function () {
    if ($scope.form.$invalid) {
        $scope.form.$setTouched();
        alert("Form is invalid.");
    }
};

In case someone wonders why would anyone want to do this kind of validation: iOS constraint validation is lacking, so ng-submit gets called even on invalid forms.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda