Angular input Validations not working - angularjs

<form name="LPform">
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;">Email ID</label>
<input class="mob-adj-inpbx" type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div ng-show="LPform.uemail.$valid">Enter a valid email.</div>
</div>
</form>
Here, I'm adding validations to 'email' and trying to display error message only when the user enters invalid email. However this is not working.

I suppose you want to show the error message if the input is invalid so
ng-show="!LPform.uemail.$valid"
Maybe you forgot to bind it to a scope variable? cause it seems to work fine.
function Ctrl($scope) {
$scope.useremail = '';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<form name="LPform">
<div class="form-row clearfix">
<label class="lbl-fld">Email ID</label>
<input class="mob-adj-inpbx" type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true" />
<div style="font-size: 11px; color: red; margin: 5px 65px;"
ng-show="!LPform.uemail.$valid">Please enter a valid email.</div>
</div>
</form>
</div>
</div>

Related

How to show error messages for min and max values of an input field with number type?

How do I set/show error messages for min and max values that I set on an input field with number type using angular js.
<input type="number" min="0.1" max="30"/>
Please use below code to show error message for min and max value in number input type field using angularjs validation.
For ng-maxlength and ng-minlength for Number input type field.
<form name="myForm">
<input type="number" name="count" ng-model="count" max="30" min="0.1">
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.min">Count should be above 0.1.</span>
<span ng-show="myForm.user.$error.max">Count should be below 30.</span>
</span>
</form>
For maxlength and minlength for Text input type field.
<form name="myForm">
<input type="text" name="username" ng-model="username" ng-minlength="5" ng-maxlength="15">
<span style="color:red" ng-show="myForm.username.$dirty && myForm.user.$invalid">
<span ng-show="myForm.username.$error.minlength">Username should be minimum 5 character.</span>
<span ng-show="myForm.username.$error.maxlength">Username should be maximum 15 character.</span>
</span>
</form>
You need to encapsulate the input inside the form and conditionally display the error messages:
var app = angular.module('app', []);
app.controller('test', function($scope) {
$scope.model = {};
});
.error {
color: red;
}
input {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
<form novalidate name="myForm">
<label for="model.data">Enter Data:</label>
<input type="number" name="data" ng-model="model.data" min="0.1" max="30" />
<div class="error" ng-show="myForm.data.$dirty && myForm.data.$error.min" ng-message="min">Unexpected minimum data</div>
<div class="error" ng-show="myForm.data.$dirty && myForm.data.$error.max" ng-message="max">Unexpected maximum data</div>
</form>
</div>
Simple :
<p class="help-block" ng-message="min || max">please enter in between 0.1 to 30.</p>
or
<p class="help-block" ng-message="min">Min 0.1 required</p>
<p class="help-block" ng-message="max">Max 30 Allowd</p>
Add required to input field.
here is SAMPLE CODE and fiddle.
https://jsfiddle.net/nc4n61bk/
<form>
<input type="number" min="0.1" max="30" required/>
<input type="submit"/>
</form>
var app = angular.module('app', []);
app.controller('test', function($scope) {
$scope.model = {};
});
.error {
color: red;
}
input {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
<form novalidate name="myForm">
<label for="model.data">Enter Data:</label>
<input type="number" name="data" ng-model="model.data" min="0.1" max="30" />
<div class="error" ng-show="myForm.data.$dirty && myForm.data.$error.min" ng-message="min">Unexpected minimum data</div>
<div class="error" ng-show="myForm.data.$dirty && myForm.data.$error.max" ng-message="max">Unexpected maximum data</div>
</form>
</div>
.valueError{
color: rgb(255, 0, 0);
padding-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
<form novalidate name="myForm">
<div class="form-field required-field">
<label for="field-value">Value</label>
<input type="number" id="field-value" name="valueInput" class="small form-control input-md ng-valid ng-dirty" ng-model="value" min="5" placeholder="Value"/>
<div class="valueError" ng-show="form.value.$dirty && form.value.$error.min "> Value must be atleast 5min</div>
</div>
</form>
</div>

Validate with AngularJS

I have a form that I want to validate with ng-click, I have some required fields e some fields like email.
<form role="form" name="cadastroEmpresa"
novalidate>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6">
<div class="form-group">
<label>Nome</label>
<input class="form-control"
placeholder="Nome da empresa"
ng-model="empresa.nome">
</div>
<div class="form-group">
<label>CNPJ</label>
<input
id="cnpj"
class="form-control"
placeholder="Entre com o CNPJ"
ng-model="empresa.cnpj">
</div>
<div class="form-group">
<label>Endereço</label>
<input type="email"
name="inputemail"
class="form-control"
placeholder="Entre com o endereço pela empresa"
ng-model="empresa.endereco">
</div>
<div class="form-group">
<label>Email</label>
<input
type="email"
class="form-control"
placeholder="Email da empresa"
ng-model="empresa.email">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Nome do Responsável</label>
<input class="form-control"
placeholder="Nome do responsável da empresa"
ng-model="empresa.nomeResponsavel" required>
</div>
<div class="form-group">
<label>Telefone</label>
<input class="form-control"
id="telefone"
placeholder="Telefone fixo"
ng-model="empresa.telefone" required>
</div>
<div class="form-group">
<label>Celular</label>
<input class="form-control"
id="celular"
ng-model="empresa.celular"
placeholder="Telefone celular">
</div>
<div class="form-group">
<label>Data de Vencimento</label>
<input class="form-control"
ng-model="empresa.dataVencimentoMensalidade"
placeholder="Data de Vencimento da Mensalidade">
</div>
</div>
</div>
</div>
</form>
I Want to validate when user clicks the button, and mark in red the field that have erros, but I'm pretty new with angular so I not sure how I do that, if some one could give me example I'll be able to finish my application. Thank you everyone.
As mentioned in Gonzalo's answer, "you should be add attribute name to the inputs that you want validate".
After it, you can use ngMessages to validate your inputs.
Here's a snippet working:
var app = angular.module('app', ['ngMessages']);
app.controller('mainCtrl', function ($scope) {
// Any JS code.
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" ></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.9/angular-messages.js"></script>
</head>
<body ng-controller="mainCtrl">
<form role="form" name="form" novalidate>
<div class="form-group" ng-class="{ 'has-error' : form.nome.$touched && form.nome.$invalid }">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6">
<div class="form-group">
<label>Nome</label>
<input name="nome" class="form-control" placeholder="Nome da empresa" ng-model="empresa.nome" required="" />
</div>
<div class="help-block" ng-messages="form.nome.$error" ng-if="form.nome.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
</div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.cnpj.$touched && form.cnpj.$invalid }">
<label>CNPJ</label>
<input id="cnpj" name="cnpj" class="form-control" placeholder="Entre com o CNPJ" ng-model="empresa.cnpj" required="" />
<div class="help-block" ng-messages="form.cnpj.$error" ng-if="form.cnpj.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.end.$touched && form.end.$invalid }">
<label>Endereço</label>
<input name="end" class="form-control" placeholder="Entre com o endereço pela empresa" ng-model="empresa.endereco" required="" />
<div class="help-block" ng-messages="form.end.$error" ng-if="form.end.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.email.$touched && form.email.$invalid }">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="Email da empresa" ng-model="empresa.email" />
<div class="help-block" ng-messages="form.email.$error" ng-if="form.email.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="col-lg-6" ng-class="{ 'has-error' : form.resp.$touched && form.resp.$invalid }">
<div class="form-group">
<label>Nome do Responsável</label>
<input name="resp" class="form-control" placeholder="Nome do responsável da empresa" ng-model="empresa.nomeResponsavel" required="" />
<div class="help-block" ng-messages="form.resp.$error" ng-if="form.resp.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.fixo.$touched && form.fixo.$invalid }">
<label>Telefone</label>
<input name="fixo" class="form-control" id="telefone" placeholder="Telefone fixo" ng-model="empresa.telefone" required="" />
<div class="help-block" ng-messages="form.fixo.$error" ng-if="form.fixo.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.celular.$touched && form.celular.$invalid }">
<label>Celular</label>
<input name="celular" class="form-control" id="celular" ng-model="empresa.celular" placeholder="Telefone celular" />
<div class="help-block" ng-messages="form.celular.$error" ng-if="form.celular.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : form.data.$touched && form.data.$invalid }">
<label>Data de Vencimento</label>
<input name="data" class="form-control" ng-model="empresa.dataVencimentoMensalidade" placeholder="Data de Vencimento da Mensalidade" />
<div class="help-block" ng-messages="form.data.$error" ng-if="form.data.$touched">
<!-- <div ng-messages-include="error-messages.html"></div> -->
</div>
</div>
<div class="form-group">
<input type="submit" name="commit" value="Criar empresa" class="btn btn-primary" ng-disabled="form.$invalid">
<a class="btn btn-default" href="#">Cancelar</a>
</div>
</div>
</form>
</body>
</html>
I would recommend you to check this tutorial also.
PS: As you may have noticed I commented all the "ng-include" (which contains the file that contains all the messages to show when input is invalid) that I put, because I don't know even if is possible to add a new "file" here in snippet, but I'm posting here almost the complete code and you can check the complete here.
error-messages.html:
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
<p ng-message="required">This field is required</p>
<p ng-message="email">This needs to be a valid email</p>
I hope it helps!!
Firstly, you should be add attribute name to the inputs that you want validate.
Then In the controller, more specifically in the $scope object, you have available a key with the name of your form, and inside this, keys associated to each input that you added a name attrubute.
Example based in your html:
angular
.module('exampleApp')
.controller('ExampleController', Controller);
Controller.$inject = ['$scope'];
function Controller($scope){
var vm = this;
var theForm = $scope.cadastroEmpresa;
console.log(theForm);
vm.handleValidation = function(){
var theForm = $scope.cadastroEmpresa;
console.log($scope);
console.log($scope.cadastroEmpresa);
}
}
Working
http://codepen.io/gpincheiraa/pen/GqEmNP
Form validation works when automatically when you submit the form. So you should add a submit type button anywhere inside the form like:
<button type="submit" class="btn btn-primary">Submit data</button>
And if you now require proper validation message and if you are using Bootstrap library, you can check out this library to provide validation messages in Angular with Bootstrap.
You just need to create a CSS for that, angular already adds the required classes for validation.
this class is added automatically to required fields, you just need to give it your style, for example:
.ng-submitted .ng-invalid {
color: #f00;
border: 1px solid #f00;
}
Codepen: http://codepen.io/giannidk/pen/Bzkkaj?editors=1001

ngMessages: how to hide or show one message after the other

I have the following code:
<div id="messageArea">
<div ng-messages="text1.$error">
<div ng-message="required">
Text1 is required ...
</div>
</div>
<div ng-messages="text2.$error">
<div ng-message="required">
Text2 is required ...
</div>
</div>
<div ng-messages="text3.$error">
<div ng-message="required">
Text3 is required ...
</div>
</div>
</div>
<div>Text1<input id="text1" ng-model="text1" name="text1" ng-required="true"></div>
<div>Text2<input id="text2" ng-model="text2" name="text2" ng-required="true"></div>
<div>Text3<input id="text3" ng-model="text3" name="text3" ng-required="true"></div>
I wanted to show one error message at a time. When the first error is solved then the next error message will show. Anyone has any idea how I can do this? Thanks.
Nice solution is use CSS and ng-class
var app = angular.module('app', ['ngMessages']);
.error-wrapper {
color: red;
}
.error-wrapper > .view {
display: block;
}
.error-wrapper > .view ~ .view{
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.7/angular-messages.min.js"></script>
</head>
<body ng-app="app">
<form ng-submit="createWallet()" name='testForm' novalidate>
<div>
<input ng-model='text1' type="text" name='text1' placeholder='text1' required>
</div>
<div>
<input ng-model='text2' type="text" name='text2' placeholder='text2' required>
</div>
<div>
<input ng-model='text3' type="text" name='text3' placeholder='text3' required>
</div>
<div class="error-wrapper">
<div ng-class="{ view: testForm.text1.$invalid }" class="error" ng-messages="testForm.text1.$error">
<div ng-message='required'>Text1 required</div>
</div>
<div ng-class="{ view: testForm.text2.$invalid }" class="error" ng-messages="testForm.text2.$error">
<div ng-message='required'>Text2 required</div>
</div>
<div ng-class="{ view: testForm.text3.$invalid }" class="error" ng-messages="testForm.text3.$error">
<div ng-message='required'>Text3 required</div>
</div>
</div>
<button>Submit</button>
</form>
</body>
</html>
It's show only the first error message with class .view, at the plunker http://plnkr.co/edit/kBSpRJLs6QA2D0jctKXB?p=preview
If you wrap the inputs in a form tag with an ID you can use ng-messages on the form to pick up errors from all the inputs. You can see this here: http://jsbin.com/tikufuvawe/2/edit.
<form name="userDetails">
<input name="userName" type="number" ng-model="number" required ng-maxlength="2" />
<textarea name="text" type="text" ng-model="text" required></textarea>
<div ng-messages="userDetails.$error">
<div ng-message="required">This is required</div>
</div>
</form>
EDIT:
I have updated my example http://jsbin.com/zadojamifo/3/edit using ng-show to hide other errors such that only one will show at a time. Its not a great solution but works for the situation described.
<div ng-messages="userDetails.number.$error">
<div ng-message="required">number is required</div>
</div>
<div ng-messages="userDetails.text.$error" ng-show="!userDetails.number.$error.required">
<div ng-message="required">text is required</div>
</div>
<div ng-messages="userDetails.other.$error" ng-show="!userDetails.number.$error.required && !userDetails.text.$error.required">
<div ng-message="required">other is required</div>
</div>
As you can see the ng-show will get bigger and bigger in size if more validation types are added and if more controls are added that require validation.
Maybe is too late but this is my solution, use ng-messages-multiple to show one or more message, angular respect the order of validation messages:
<form name="loginForm" ng-submit="login()">
<label>Email</label>
<input required name="email" type="email" ng-model="email">
<div ng-messages="loginForm.email.$error" ng-show="loginForm.email.$dirty && loginForm.email.$invalid" ng-messages-multiple>
<div ng-message="required">El email es requerido!</div>
<div ng-message="email">El email debe cumplir con el formato: email#dominio.com!</div>
</div>
<label>Contraseña</label>
<input required name="password" type="password" ng-model="password" ng-pattern="passwordPattern" md-maxlength="12">
<div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$dirty && loginForm.password.$invalid">
<div ng-message="required">La contraseña es requerida!</div>
<div ng-message="pattern">Se requieren de 6 a 12 caracteres, por lo menus un dígito, una letra mayuscula y una minúscula</div>
</div>
<div layout="row" layout-align="center center">
<button ng-disabled="loginForm.$invalid>Login</button>
</div>
</form>
You can do something like this
<div id="messageArea">
<div ng-messages="number.$error">
<div ng-message="required">
Number is required ...
</div>
</div>
<div ng-messages="text.$error" ng-if="!number.$error">
<div ng-message="required">
Text is required ...
</div>
</div>
In this case you show the second block of messages only if the first one does not exists (and it's hidden if number.$errors exists)
This sample (http://www.yearofmoo.com/2014/05/how-to-use-ngmessages-in-angularjs.html) uses a follow solution:
<div ng-messages="my_form.first_name.$error"
ng-if="interacted(my_form.first_name)">
$scope.submitted = false;
$scope.submit = function() {
$scope.submitted = true;
};
$scope.interacted = function(field) {
return $scope.submitted || field.$dirty;
};
If you don't want to show on page load but either on page submit or on change of value then use
<form name="frmSome">
<div ng-messages="userDetails.$error"
ng-if='frmSome.userName.$dirty || frmSome.$submitted'>
<span ng-message="required">Name is Required</span>
<span ng-message="maxlength">Max. 100</span>
</div>
<input name="userName" type="text"
ng-model="model.name"
ng-required='true'
ng-maxlength="30" />
..............................
..............................
<input type='submit' value='Submit' />
</form>
If you touch the text box it will be "dirty"
if try to submit the page "Submitted"
It works on the name not the model

How to display form errors just when input are invalid and dirty?

I have working with AngularJS. I have the following form :
<html lang="en" ng-app="app">
...
<div ng-controller="RegisterController">
<h3>Register</h3>
<form name="registerForm" class="form-horizontal panel-body" novalidate="novalidate">
<form name="registerForm" class="form-horizontal panel-body" novalidate="novalidate">
<div class="form-group">
<label name="firstname" class="col-md-2 control-label">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" name="firstname" ng-model="user.firstname" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label name="lastname" class="col-md-2 control-label">Last Name</label>
<div class="col-md-4">
<input type="text" class="form-control" name="lastname" ng-model="user.lastname" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label name="email" class="col-md-2 control-label">Your email</label>
<div class="col-md-4">
<input type="email" class="form-control" name="email" ng-model="user.email" placeholder="Email Address" required>
</div>
<div class="col-md-2">
<span ng-show="showError(userInfoForm.email, 'email')" ...>
You must enter a valid email
</span>
<span ng-show="showError(userInfoForm.email, 'required')" ...>
This field is required
</span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<button class="btn btn-sm btn-primary" ng-disabled="!canRegister()" ng-click="submit()">Register</button>
</div>
</div>
I have also app.js file which contains configuration and controller code, i just paste the controller code:
app.controller('RegisterController', function($scope) {
$scope.getCssClasses = function(ngModelContoller) {
return {
error: ngModelContoller.$invalid && ngModelContoller.$dirty,
success: ngModelContoller.$valid && ngModelContoller.$dirty
};
};
$scope.showError = function(ngModelController, error) {
return ngModelController.$error[error];
};
$scope.canRegister = function() {
return $scope.registerForm.$dirty &&
$scope.registerForm.$valid;
};
});
My problem is that when i load the register page ( the page which contains the form), i have the two errors are printed :
You must enter a valid email This field is required
I am wondering how to do print the error when the input is dirty and invalid and desapear when the input text is valid.
Thansk for your help
Set class "validate" on each input class, and add style.css, like:
.validate.ng-dirty.ng-invalid {
border: 2px solid red;
}
.validate.ng-dirty.ng-valid {
border: 2px solid green;
}
Here is one way (of many) to validate forms http://plnkr.co/edit/u0Wr0dza8lGnVrgwrUEa
$error is the object of errors where the key is the field validation name and value is the actual error message
<input type="email" name="emailName" ng-model="email" required>
for this example myForm.emailName.$error.email = true if email is not matched with format.
myForm.emailName.$error.required = true if you haven't added anyhting in input field
you can check valid or not of the field directly by using myForm.emailName.$valid but
the problem in your case is they want to show the user what is the error by having two cases. so they entered into $error object to check for the error is required email or invalid email
1.Email is required.
2.Invalid email address.
so they used $error object.
this is how myForm.emailName looks:
{"$viewValue":"ss","$validators":{},"$asyncValidators":{},"$parsers":[],"$formatters":[null],"$viewChangeListeners":[],"$untouched":false,"$touched":true,"$pristine":false,"$dirty":true,"$valid":false,"$invalid":true,"$error":{"email":true},"$name":"emailName","$options":null}
check this out

Unable to determine why form won't submit

I've created a basic angular form and can't determine why it's not submitting.
http://contact-info.checkoutbiblebowl.com/
The form validation is valid and it still won't submit. I feel like I've overlooked something silly, but have looked at this over the last few days and can't figure out what it is. Any suggestions?
<form method='post' action='' name='form' novalidate ng-controller="myController">
<div class="row form">
<div class="form-inline">
<div class="form-row">
<label class="form-label" style='margin-top: 20px'>Name</label>
<div class="form-item">
<div style="float: left">
First<br/>
<input type="text" ng-model="firstName" name="firstName" class="small" style="width: 200px" maxlength="32" required>
<div ng-cloak ng-show="form.firstName.$error.required" class="required">First name is required</div>
</div>
<div style="float: left; margin-left: 1em">
Last<br/>
<input type="text" ng-model="lastName" name="lastName" class="small" style="width: 200px" maxlength="32" required>
<div ng-cloak ng-show="form.lastName.$error.required" class="required">Last name is required</div>
</div>
<div style="clear:both"></div>
</div>
</div>
<div class="button-row">
<button ng-disabled="!form.$valid" type="submit" class="btn" ng-click="debug()">Submit</button>
</div>
</div>
</div>
</form>
My Controller:
<script type="text/javascript">
angular.module('contact', []).
controller('myController', function ($scope) {
$scope.debug = function () {
console.log($scope.form);
}
});
</script>
I think you just need to specify the action explicitly, not with an empty string otherwise angular will prevent the submission.
http://docs.angularjs.org/api/ng.directive:form
like so:
http://plnkr.co/edit/WtP03BFVyEsnOqf3n8a4?p=preview

Resources