Search code examples
angularjsonsen-ui

AngularJS input validation


I have this html

<ons-input id="username" modifier="underbar" name="username" placeholder="Nombre de usuario" float ng-model="page.username" ></ons-input>

<ons-input id="password" modifier="underbar" name="password" type="password" placeholder="Contraseña" float ng-model="page.password" ></ons-input>
<img ng-click="login()" class="boton-login" src="img/boton_acceder.png"></img>

my login function looks like this.

$scope.login = function(){
    if ($scope.page.username.length==0 || typeof $scope.page.username =="undefined"){
       ons.notification.alert("Error");
 }else{
      //More code.
   }
}

I am getting error: Cannot read property 'username' of undefined, i have tried with angularjs classes of $dirty, and $error, but still getting the same problem, so if anybody knows how to know if my input is empty when I click on the button, help me please


Solution

  • It's happening because you didn't defined page.

    I recommend you to do this way:

    app.controller('demoCtrl', function ($scope) {
        $scope.page = { username: new String() };
    
        $scope.login = function () {
            if ($scope.page.username !== undefined)
                if ($scope.page.username.length === 0)
                    console.log('error');
                else
                    console.log('ok');
    
        }
    });
    

    Demo