how to validate on form submit using AngularJS - angularjs

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;
};
});

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!

Related

Clear ng-model then Update ng-model with new value

Angular and Ionic Application
I have a form that has a lot of <select> elements, The form offers the user to select from a list or if the <option> = 'Other' then I show another <input> to enter the value. I then save the value to another ng-model.
<select data-ng-model="minor.tests.liveEarth"
name="minorTestLiveEarth"
required>
<option></option>
<option>>200</option>
<option>>299</option>
<option>>500</option>
<option>>1000</option>
<option>Other</option>
</select>
</label>
<label class="item item-input item-stacked-label" ng-show="minor.tests.liveEarth === 'Other'">
<span class="input-label">Please Specify</span>
<input type="text"
placeholder="live earth other"
ng-maxlength="10"
data-ng-model="minor.tests.liveEarthOther"
name="minorTestLiveEarthOther">
</label>
I originally used <datalist> but doesn't show up on iOS.
I assigned the liveEarthOther to the same as the <select> liveEarth but it has 'Other' assigned to the ng-model, which then the user has to delete the input value Other before entering their value.
I have looked for a combobox kind of control but haven't found one that works properly.
How could I make this into a directive or any thing suitable that could perform the renaming without the user having to delete the value.
I want to use this functionality many times in the application I am building.
You may have overcomplicated things by re-using the ngModel. If you change the value minor.tests.liveEarth you'll mess up your select because anything other than the given values will cause nothing to be selected. But if you don't change minor.tests.liveEarth then you'll have to delete it when the user fills in the text input. This would then also mess up the select box!
What I would do is record the value of the text input to a different variable. Keep the ng-show="minor.tests.liveEarth === 'Other'" as it is, but change your input to
<input type="text"
placeholder="Fill in your other live earth"
ng-maxlength="10"
data-ng-model="tempVar" />
This way the input will be still be recorded, but the select won't be messed up on the ngModel change. Due to the placeholder, the user will know that they have to fill in the text box.
In your js, you'll have to create a validating function when the form is submitted along the lines of:
var validateLiveEarth = function(){
if(minor.tests.liveEarth === "Other"){
//check that tempVar meets validation
//assign tempVar to whatever form you're sending
}
}

Angularjsjs form required field don't validate on load

I have a form text field it is required but its initial value is an empty string, so when I load the form the controller validates the form field and marks it as error, I want on the initial load not to validate the form field only after an onblur event.
<input data-ng-model="MyCtrl.opportunity.company" type="text" class="form-control" name="company" ng-model-options="{ updateOn: 'blur' }" required />
And here is the fiddle http://jsfiddle.net/petran/Lvc0u55v/725/
I know I can call $setValidity on controller I am looking for a more elegant solution if there is exist.
Add this statement to ng-class statement:
...&& addOpportunityForm.company.$dirty...
Use the $pristine for validation tool in AngularJS. This will allow the funtion to wait until the input field has been changed before testing the condition. You can learn more about form states here: Angular Form States

Create dynamic form and validate/post it in AngularJS

I have in AngularJS a login form with a username and password input field. Above there is a button to load the register form. Then an email field will be added to the form.
But when I submit the register form, only the username and password input fields will be posted and not the email field.
Send Data after Login: {"username":"test","password":"test"}
Send Data after Register: {"username":"test","password":"test"}
Do you know why?
I created a Plnkr to demonstrate the problem:
http://embed.plnkr.co/HBEfITT3SNSZv44hj2x3/preview
Your additional field is inside an element with
ng-if="register"
ng-if is a directive that creates its own scope. So, when something is entered into the field <input ng-model="email" ...>, an email attribute is created and populated in the ng-if scope, instead of being created in the controller scope.
Rule of thumb: always have a dot in your ng-model, and always initialize the form model in the controller:
$scope.formModel = {};
<input ng-model="formModel.email" ...>
This will also make things simpler, since to post the form, all you'll have to do is something like
$http.post(url, $scope.formModel).then(...);

angular form validation - ng-valid to start

I'm using angular-auto-validate and am having some state management issues. I have a multipart form where some fields are required (name/email address) and the user is able to go "back" to change answers. Basically, I have a partial for every stage in the form which is working well, with one exception. The continue button is disabled if the field is invalid. I tried simply using the $valid identifier, but when the partial loads, each field begins with ng-valid so I can either use $touched or $pristine. Problem is, when the user goes back, the value that has binded to a data source is valid, but the field isn't touched so the continue button doesn't activate. Sample code (this is generated code after I've hit the "back" button):
<input type="text" name="name" ng-minlength="3" ng-model="myModel" placeholder="Your First Name" ng-focus="inputFocused()" ng-pattern-err-type="" ng-model-options="{updateOn: 'blur'}" class="ng-valid ng-valid-pattern ng-valid-minlength">
and the button:
Continue
How can I either disable the default ng-valid or identify a condition where the value is being populated by the controller?
I think you should use ng-dirty/pristine. You can manually set the condition of the form as the user navigates.
When you populate your form data you can do something like:
if($scope.myForm.data) {
$scope.myForm.$setDirty
}
Your button:
Continue

$scope.var giving undefined in angularjs

I am using angularjs to do client side validation on a textbox where I need input as alphanumeric chars only. If the textbox is left empty or non-alphanumeric char is entered, the submitform sends 'false' to JS which is desired but the problem is it doesn't pass the non-alphnumeric char itself (in the scope).
JSP file:
<form name="addressForm" method="post"
ng-submit="submitform(addressForm.$valid)" novalidate>
..
<input ng-model="address" type="text"
**ng-pattern**="/^[a-zA-Z0-9 ]*$/" required="true"/>
JS file:
$scope.submitform= function(isValid){
var inputAddr = $scope.address;
alert(inputAddr); //coming as undefined
...
Now when I input an alphanumeric character in input box 'address' in jsp it gives me undefined on alerting it in JS (probably because of pattern which filters the char being non-alphanumeric). If I remove ng-pattern, it passes the submitForm passes 'true' as if every input is "as expected". The reason I want to access $scope.address is to check and value and display different error message for "empty" and a "non-alphanumeric" validation.
Any help is appreciated !
When the model is not valid, the value is not assigned to the model. If you want to see what the user has typed, you need to check $viewValue:
You must to add name attribute to input, so change your input html to:
<input ng-model="address" type="text" name="address"
ng-pattern="/^[a-zA-Z0-9 ]*$/" required="true"/>
And change your submit function to
$scope.submitform = function(isValid) {
console.log($scope.addressForm.address.$viewValue);
}
It sounds like you just need to know what the validation error is.
You can check the $error property the FormController (addressForm in your case) to see what validations passed or failed.
For example, if the input is empty, then the "required" validation will have failed and addressForm.$error.required will be an Array containing the inputs that failed this validation.
If the "required" validation succeeded, then addressForm.$error.required will just be false.
You can use this in angular expressions quite easily:
<p ng-show="addressForm.$error.required">This field is required.</p>
Or you can access the form through the $scope object that is associated with the view:
if ($scope.addressForm.$error.required) {
// required validation failed
}
Check out the documentation for FormController and ngModelController.

Resources