4

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>
1

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

what is the use of contact_form.first_name.$dirty?
It is used to check case if input was interacted or not docs.angularjs.org/guide/forms
1

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>

Comments

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.