-2

I am very much new in angular js.I want to validate and post the form data using angular js on submit.I searched google but most of them was disable the button on load ,after completing the form with valid data the button enable but I want to show error messages on form submit.

Here is My form snapshoot

I have tested with two text fields one is name and other is email but I want to proper messages for each fields e.g for email,phone no (valid format) and empty fields now I get only empty field message.

 <span class="error-message"
 ng-show="showMessage(frmReg.name)">
 Please complete this field.</span> 
var app=angular.module('regForm',[]);

app.controller('FormController',function($scope,$http){
    $scope.frmRegField={};

    $scope.frmSubmit=function(){
        angular.forEach($scope.frmReg.$error.required, function(field) {
          field.$setDirty();
        });

        // $http({
            // method:"POST",
            // url:"form_submit.php",
            // data:$scope.frmRegField
            // }).success(function(data){

            // });
    };

    $scope.showMessage=function(input){
        console.log(input.$$attr.name);
         var show = input.$invalid && (input.$dirty || input.$touched);
         return show;

    };
});
3
  • Please share your code.So we will give you better suggestions. Commented Aug 1, 2018 at 7:47
  • Use logical statements to determine if the event handler is called in angular. Not much more advice I can give without a specific code example. Commented Aug 1, 2018 at 8:05
  • It is hard to see how the form connects to the controller without seeing the HTML for the form. Create a Minimal, Complete, and Verifiable example with just one input element and one submit button. Commented Aug 1, 2018 at 17:19

2 Answers 2

2

You could use either class or state to do what you need

Input fields have the following states:

  • $untouched The field has not been touched yet
  • $touched The field has been touched
  • $pristine The field has not been modified yet
  • $dirty The field has been modified
  • $invalid The field content is not valid
  • $valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

  • $pristine No fields have been modified yet
  • $dirty One or more have been modified
  • $invalid The form content is not valid
  • $valid The form content is valid
  • $submitted The form is submitted

The following classes are added to, or removed from, input fields:

  • ng-untouched The field has not been touched yet
  • ng-touched The field has been touched
  • ng-pristine The field has not been modified yet
  • ng-dirty The field has been modified
  • ng-valid The field content is valid
  • ng-invalid The field content is not valid
  • ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
  • ng-invalid-key Example: ng-invalid-required

The following classes are added to, or removed from, forms:

  • ng-pristine No fields has not been modified yet
  • ng-dirty One or more fields has been modified
  • ng-valid The form content is valid
  • ng-invalid The form content is not valid
  • ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
  • ng-invalid-key Example: ng-invalid-required

The classes are removed if the value they represent is false.

Give the form a name:

<form name="myForm">

And a name for the input to:

<input type="text" name="myName">

Then use ng-show/ng-if in your span:

<span class="error-message" ng-show="myForm.myName.$touched && myForm.myName.$invalid">
 Please complete this field.
</span> 

You can use ng-disabled to validate submit too:

<input type="submit" value="Submit" ng-disabled="myForm.$invalid">

Hope this helps. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

0

I had the same problem trying to validate a from for creating a new user with four fiels: firstName, lastName, age and emailAddress.

I tried to use the $invalid default state, but it does not feel the correct format of an email address: {some characters}@{some characters}.{some characters}.

So I was able to solve it with ng-pattern. Here a snippet of my code.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<body ng-app="">
<form name="newUserModalForm">
 <div>
  <input type="text" name="Name" placeholder="firstName" ng-model="new_first_name_modal" ng-pattern="/^[a-zA-Z ,.'-]+$/" required>


            <span style="color:Red" ng-show="newUserModalForm.Name.$error.required"> Required! </span>
            <span style="color:Red" ng-show="newUserModalForm.Name.$dirty && newUserModalForm.Name.$error.pattern"> Invalid name! </span>

        </div>
        <div>
            <input type="text" name="Surname" placeholder="lastName" ng-model="new_last_name_modal" ng-pattern="/^[a-zA-Z ,.'-]+$/" required>
            <span style="color:Red" ng-show="newUserModalForm.Surname.$error.required"> Required! </span>
            <span style="color:Red" ng-show="newUserModalForm.Surname.$dirty && newUserModalForm.Surname.$error.pattern"> Invalid surname! </span>

        </div>
        <div>
            <input type="text" name="Age" placeholder="Age" ng-model="new_age_modal" ng-pattern="/^[0-9]{1,3}$/" required>
            <span style="color:Red" ng-show="newUserModalForm.Age.$error.required"> Required! </span>
            <span style="color:Red" ng-show="newUserModalForm.Age.$dirty && newUserModalForm.Age.$error.pattern"> Insert
                a valid age! </span>

        </div>
        <div>
            <input type="text" name="Email" placeholder="Email" ng-model="new_email_modal"
                ng-pattern="/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/"
                required>
            <span style="color:Red" ng-show="newUserModalForm.Email.$error.required"> Required! </span>
            <span style="color:Red" ng-show="newUserModalForm.Email.$dirty && newUserModalForm.Email.$error.pattern">
                Insert a valid email address! </span>
        </div>
</form>
</body>
</html>

I used regular expressions for validating the input fields.

Name and surname: ^[a-zA-Z ,.'-]+$. It matches all names with all letters, also uppercase, no numbers and characters like . ' and - .

Age: ^[0-9]{1,3}$. It matches all numbers, max 3 digit.

Email:^[\w-]+(.[\w-]+)@([a-z0-9-]+(.[a-z0-9-]+)?.[a-z]{2,6}|(\d{1,3}.){3}\d{1,3})(:\d{4})?$. I found this here : https://stackoverflow.com/a/42452767/18420603

You can test the code here: https://codepen.io/bbbgl/pen/XWxLoNe

Hope this will help you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.