Required field Validation on input on image button click

Issue

The validation works correctly when I have it on the button with type submit. However, I have an image that acts like an image button for me and I want the project name to be filled before the user clicks on the image. Can someone help me achieve this please?

  <form name="userForm">
            <table>
                <tr>
                    <td>
 <%-- <button type="submit" data-ng-click="addAnswers($event)" data-ng-disabled="userForm.$invalid">Save</button>--%>
                    <img src="/SaveBttn.png"
                            style="width: 100px; height: 50px;" data-ng-click="addAnswers($event)" />
                    </td>
                    <td>
                        <img alt="" onclick="Close()" src="/Close.png"
                            style="width: 100px; height: 50px;" />
                    </td>
                </tr>
            </table>
            <div>
            <input type="text" required name="ProjectName" placeholder="ProjectName"  data-ng-model="name" maxlength="250" style="width: 400px;" />
            </div>  
</form>‚Äč

Solution

you must setvalidity in addAnswers action.

var app = angular.module("app",[]);

app.controller("ctrl",function($scope){
  
  $scope.name = "";
  $scope.addAnswers = function($event,userForm){
    
    if($scope.name == ""){
       $scope.userForm["ProjectName"].$setValidity('empty', false);
      }
    else{
       $scope.userForm["ProjectName"].$setValidity('empty', true);
     
      }
    
    }
  
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form name="userForm">

                <table>
                    <tr>
                        <td>
                        <img src="/SaveBttn.png"
                                style="width: 100px; height: 50px;" data-ng-click="addAnswers($event)" />
                        </td>
                        <td>
                            <img alt="" onclick="Close()" src="/Close.png"
                                style="width: 100px; height: 50px;" />
                        </td>
                    </tr>
                </table>
        <div>
        <input type="text" required name="ProjectName" ng-model="name" placeholder="ProjectName" />
          <span ng-show="userForm.ProjectName.$error.empty">This feild is empty.</span>
</div>           
  </form>
  </div>

Answered By – Hadi J

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.