1

I am writing a simple form, where I want to save the form result into an array, having both the first name and last name updated, if either or both fields are left empty it should throw an alert message. And the array should not store empty values and I wanted to handle this on the client side. I am kind of confused on how to keep a check on the input values before storing them. Here is the code snippet: https://jsbin.com/guduwakeji/edit?html,js,output

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
  $scope.ele = [];
  $scope.updateDetails = function(ele) {
    if (!ele.firstname && !ele.lastname) {
      alert("Ele cannot be empty");
    } else {
      ele.push({
        'firstname': '',
        'lastname': ''
      });
      alert(ele.firstname + "  " + ele.lastname);
    }
    console.log(ele);
  };

});
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body ng-app="myApp">
  <div ng-controller="formCtrl">
    <div>
      First Name:
      <input type="text" ng-model="ele.firstname">
      </br>
      Last Name:
      <input type="text" ng-model="ele.lastname">
      <br/>
      <input type="button" value="Submit" ng-click="updateDetails(ele)">
    </div>
  </div>
</body>

</html>

2
  • Please add the code in question itself. Commented Jun 28, 2016 at 6:42
  • use ng-pristine, ng-dirty ,ng-valid, ng-invalid Commented Jun 28, 2016 at 6:44

1 Answer 1

1

use this code

i figure out this way to validate your form

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
  $scope.ele={};
    $scope.updateDetails = function(ele){
    if(ele.firstname &&  ele.lastname)
     { console.log(ele);}
      else{
        alert("empty field not allowed");
      }
    };

});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this also works for me. Thank you. But I have this doubt, we can also use required attribute in the input field right? Along with the model validation.
its not working because its not html form required is only work with html form hope you got it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.