Search code examples
javascripthtmlangularjserror-handlingrequiredfieldvalidator

Custom Error Validation Message Not Showing


I am doing error validation in Angular as follows.

<select ng-model = "color" class = "form-control"
    ng-options = "color as color for color in colors" required>
    <option value="">Choose an option</option> 
</select>

<span ng-show="serviceForm.color.$error.required"> My custom error message </span>

The error validation shows up as expected, however, the custom message does not. Instead, I get the following.

enter image description here

This looks nice but how do I replace it with my custom message? It'd be cool if I know where that is coming from so I can edit it.

In addition, my custom message appears if I take out

<option value="">Choose an option</option> 

and then it always appears. Why is this?


Solution

  • Working Plnkr

    You can replace HTML5 validation message of that specific field with space on form submit. It will prevent displaying the message and will not affect other HTML5 validation message.

    JavaScript:

    $scope.ValidateInput = function(){
        var email = document.getElementById("colorId");
    
        if (email.validity.valueMissing) {
            email.setCustomValidity(" ");
        } else {
            email.setCustomValidity("");
        }
      }
    

    HTML:

    <form name='serviceForm'>
          <select name='color' id='colorId' ng-model = "color" class = "form-control"
        ng-options = "color as color for color in colors" required>
             <option value="">Choose an option</option> 
          </select>
    
         <span ng-show="serviceForm.color.$error.required"> My custom error message </span>
         <input type='submit' ng-click='ValidateInput()' value='Submit'>
    </form>