0

I want to validate the fields. When user doesn't enter anything in the field and click on submit button, could not able to validate it.

Demo

Please see the sample below:

    $scope.validateFields = function(){
            alert("Comments " + $scope.comments); //When fields are blank and click on submit, it shows undefined
              if($scope.comments === 'undefined'){
                 alert("comments are blank");//not printed
                 $scope.comments = 'undefined';
            }
            if( $scope.comments.length == 0){
              alert("comments length is zero"); //not printed
              $scope.comments = 'undefined';
            }

In the above sample code, when click on submit button without entering anything in the comments fields, it is not entering the if condition. I want to assign $scope.comments='undefined' when the comments field is blank and clicked on submit button.

Ravi Ubana
  • 397
  • 5
  • 26
user7833845
  • 83
  • 2
  • 11

3 Answers3

0

Use below code. You can initialize the $scope variable at the time of controller loading.

app.controller('myCtrl',function($scope,$http){

      $scope.validateFields = function(){
          if($scope.comments){
             alert("comments are blank");
        }
        if( $scope.comments.length == 0){
          alert("comments length is zero");
        }
//      alert("validate"+ $scope.comments.length); 
      } 

      function init() {
        $scope.comments = '';
      }

      init();


    });

Check plunkr

Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
0

The first problem is you are checking if $scope.comments matches the string undefined, rather then checking if it is currently defined on the given scope.

if($scope.comments === undefined) {
    alert("comments are blank");//not printed
    $scope.comments = '';
}

Notice I just removed the quotes around undefined to achieve this. You can even use the shorthand for this which checks whether the value is falsey. You can find a full list of falsey values online but a couple of them are an empty string or undefined.

if(!$scope.comments) {
    alert("comments are blank");//not printed
    $scope.comments = '';
}

Next, you can avoid this completely by just initializing your $scope with comments like so.

var app=angular.module("myApp",[]);
app.controller('myCtrl', function($scope,$http) {
    $scope.comments = '';

    $scope.validateFields = function() {
        alert("Comments " + $scope.comments);
        if(!$scope.comments){
            alert("comments are blank");
        }
        else {
            alert("comments exist");
        }
    }
});
Spidy
  • 39,723
  • 15
  • 65
  • 83
0

The best way to check for a null values is

if ( testVar !== null )
{
    // do action here
}

for undefined

if ( testVar !== undefined )
{
    // do action here
}

You can assign a avariable with undefined.

testVar = undefined;

Please refer to falsey values in javascript

Santosh
  • 875
  • 5
  • 14
  • 33