Reputation: 3964
How to hide a default error message in AngularJs? I tried display:none; . But, it won't work. I'm new to AngularJS. I want to hide the default error message and I want to show the error message when user onfocus the input textbox.
<p>
<label for="first_name">First Name</label>
<input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
<span class="error" ng-messages="contact_form.first_name.$error">
<span ng-message="required">First name should not be empty</span>
<span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
</span>
</p>
Upvotes: 4
Views: 4370
Reputation: 5055
This is what you need, contact_form.first_name.$dirty
is used to check if field was changed or not
<form name="contact_form" novalidate>
<p>
<label for="first_name">First Name</label>
<input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
<span class="error" ng-messages="contact_form.first_name.$error">
<span ng-message="required" ng-show="contact_form.first_name.$error.required && contact_form.first_name.$dirty">First name should not be empty</span>
<span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
</span>
</p>
</form>
Upvotes: 3
Reputation: 19070
In your controller you can create a variable to determine if the form have been sumbitted:
app.controller('NameController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.formProcess = function(form) {
$scope.submitted = true;
// logic
}
}]);
Than in your view:
<form ng-submit="formProcess(form)">
<p>
<label for="first_name">First Name</label>
<input type="text" name="first_name" id="first_name" ng-model="firstName" ng-pattern="/^[a-zA-Z\s]*$/" required/>
<span class="error" ng-if="submitted" && ng-messages="contact_form.first_name.$error">
<span ng-message="required">First name should not be empty</span>
<span ng-message="pattern" ng-show="contact_form.first_name.$error.pattern">Only alphabets allowed</span>
</span>
</p>
<p>
<button class="btn btn-secondary" type="submit">Send</button>
</p>
</form>
Upvotes: 1