Two Forms on one page Angularjs - angularjs

I am creating a web app using AngularJS. I have two forms on one page. I want validate form one by one.My problem is validations occurs on both the form When I submit first form.Here is my code:
submitAddRouter : function(router){
var form = router.form;
// Show error messages and exit.
if (form.$invalid) {
if (form.$pristine) {
form.$setDirty();
}
}
submitConfigureRouter : function(configureRouter){
console.log(configureRouter);
var form = configureRouter.form;
// Show error messages and exit.
if (form.$invalid) {
if (form.$pristine) {
form.$setDirty();
}
}
Here is Form
<form name="configureRouter.form" autocomplete="off" data-ng-submit="configureRouter.submitConfigureRouter(configureRouter)" novalidate>
<select class="selectbox_menulist" required name="region" ng-model="configureRouter.region">
<option value="" selected disabled>{{'popup.configureRouter.tabs.parameters.form.region' | translate}}</option>
<option ng-repeat="regions in RegionList">{{regions.name}}</option>
</select>
<div class="col-xs-10" ng-class="{ 'has-error' : configureRouter.form.description.$invalid && !configureRouter.form.description.$pristine }">
<textarea class="form-control" maxlength="255" required name="description" ng-model="configureRouter.description" placeholder="{{'popup.configureRouter.tabs.parameters.form.description' | translate}}"></textarea>
</div>
<form name="router.form" autocomplete="off" data-ng-submit="configureRouter.submitAddRouter(router)" novalidate>
<div class="col-xs-12 add_new_route">
<h2>New Routes</h2>
<fieldset class="form-group">
<label for="" class="col-xs-2 text-label">Name</label>
<div class="col-xs-6" ng-class="{ 'has-error' : router.form.name.$invalid && !router.form.name.$pristine }">
<input type="text" name="name" required ng-model="router.name" class="form-control" placeholder="Name" />
</div>
</fieldset>
<button class="btn btn-green">Save</button>
</form>
<button class="btn btn-white" type="button" ng-click="configureRouter.closeConfigureRouterModal()">
</form>

You need to have at least two controllers for validation, each form must have its own controller. Else its going to validate both forms.

Related

ng-show not working angular form validation

I am trying to show error message after validation. Backend is php and it is returning the data i can see that in network tab.
Here are the codes.
function formRegister($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
$scope.registerForm = function() {
$http({
method : 'POST',
url : 'registerexec.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
//{{$scope.errorFname}}
$scope.erroracType = data.errors.actype;
$scope.errorFname = data.errors.Fname;
$scope.errorLname = data.errors.Lname;
$scope.errorEmail1 = data.errors.email1;
$scope.errorPassword1 = data.errors.password1;
$scope.errormobile = data.errors.mobile;
$scope.message1 = data.message1;
}
});
};
}
Here is the form.
<div class="feature-box wow animated flipInX animated">
<div id="validation-errorss" ng-show="message1" ><div class="alert alert-danger"><strong >{{ message1 }}</strong><div></div></div>
</div>
<div class="panel-body" id="success"></div>
<font size="4" color="#fff">Register</font>
<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
<select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
<option value="" selected="selected" >I am</option>
<option value="1">a user</option>
<option value="2">an admin</option>
</select>
<span class="help-block" ng-show="errorName">{{ erroractype }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorFname }">
<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<span class="help-block" ng-show="errorFName">{{ errorFname }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<span class="help-block" ng-show="errorLName">{{ errorLname }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<span class="help-block" ng-show="errorEmail1">{{ errorEmail1 }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<span class="help-block" ng-show="errorPassword1">{{ errorPassword1 }}</span>
</div>
<div class="form-group" ng-class="{ 'has-error' : errormobile }">
<input type="text" id="mobile" name="mobile" placeholder="Mobile Number (Without +91)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
<span class="help-block" ng-show="errormobile">{{ errormobile }}</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
Problem is when form get validated in backend. The array messages are not showing in .
Here are the validation errors which found in firebug.
errors:Object Fname:"Your First name must be between 3 to 30
characters!" Lname:"Your Last name must be between 3 to 30
characters!" Password1:"Your password must be between 6 to 30
characters!" success:false
Add novalidate attribute to form tag
<form novalidate>
You might use this if you plan to do your own client-side validation, if you want to create your own validation bubbles, or if you plan to go all server-side validation (which you need to do anyway).

How to show error messages for Checkbox set and Radio set using ng-messages?

I have been trying to validate Checkbox set and Radio set and show the error messages using ng-messages directive but it does not work out as expected. The ng-messages does not show the error message at all. I am populating error messages using an html file. Up until the errors are resolved, the submit button will be disabled in my form.
How can I show error messages for the Checkbox set and Radio set when:
One option is not selected in Radio set?
At least one option is not selected in Checkbox set?
Scaling the check for the Checkbox set so that we can check at least 2 or more are checked, etc.?
Here's my form:
<form name="userForm" ng-submit="submitForm()" novalidate>
<div class="form-group" ng-class="{ 'has-error' : userForm.subscribe.$invalid && !userForm.subscribe.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="subscribe1" value="option1" name="subscribe[]" ng-model="user.subscribe" required> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe2" value="option2" name="subscribe[]" ng-model="user.subscribe" required> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe3" value="option3" name="subscribe[]" ng-model="user.subscribe" required> 3
</label>
<div class="help-block" ng-messages="userForm.subscribe.$error" ng-show="userForm.subscribe.$invalid">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.gender.$invalid && !userForm.gender.$touched }">
<div class="radio">
<label>
<input type="radio" name="gender" value="male" ng-model="user.gender" />
male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="female" ng-model="user.gender" />
female
</label>
</div>
<div class="help-block" ng-messages="userForm.gender.$error" ng-show="userForm.gender.$invalid">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-success " ng-disabled="userForm.$invalid">Submit</button>
</form>
messages.html
<span ng-message="required">This field is required</span>
<span ng-message="minlength">This field is too short</span>
<span ng-message="maxlength">This field is too long</span>
<span ng-message="required">This field is required</span>
<span ng-message="email">This needs to be a valid email</span>
controller.js
angular.module('myApp', ['ngRoute', 'ngAnimate', 'ngMessages']);
angular
.module('myApp')
.controller('HomeCtrl', HomeCtrl);
HomeCtrl.$inject = ['$scope'];
function HomeCtrl($scope) {
$scope.userForm = {};
}
Payment Checkbox set:
<div class="form-group" ng-class="{ 'has-error' : userForm.payment.$invalid && userForm.payment.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="payment1" value="Visa" name="payment" ng-blur="doTouched()" ng-model="user.payment[1]" ng-required="!someSelected(user.payment)"> Visa
</label>
<label class="checkbox-inline">
<input type="checkbox" id="payment2" value="Mastercard" name="payment" ng-blur="doTouched()" ng-model="user.payment[2]" ng-required="!someSelected(user.payment)"> Mastercard
</label>
<label class="checkbox-inline">
<input type="checkbox" id="payment3" value="Cash" name="payment" ng-blur="doTouched()" ng-model="user.payment[3]" ng-required="!someSelected(user.payment)"> Cash
</label>
<div class="help-block" ng-messages="userForm.payment.$error" ng-show="userForm.payment.$invalid && userForm.payment.$touched">
<div ng-messages-include="home/messages.html"></div>
</div>
</div>
Check this sample:
http://plnkr.co/edit/2w0lIf?p=preview
The check boxes list use the ng-required directive with the someSelected function (defined in the controller) which checks if at least one item is selected:
<div class="form-group" ng-class="{ 'has-error' : userForm.subscribe.$invalid && userForm.subscribe.$touched }">
<label class="checkbox-inline">
<input type="checkbox" id="subscribe1" value="option1" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[1]" ng-required="!someSelected(user.subscribe)"> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe2" value="option2" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[2]" ng-required="!someSelected(user.subscribe)"> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="subscribe3" value="option3" name="subscribe" ng-blur="doTouched()" ng-model="user.subscribe[3]" ng-required="!someSelected(user.subscribe)"> 3
</label>
<div class="help-block" ng-messages="userForm.subscribe.$error" ng-show="userForm.subscribe.$invalid && userForm.subscribe.$touched">
<div ng-messages-include="messages.html"></div>
</div>
</div>
The option button group is easier and use the ng-required directive with the condition !user.gender:
<div class="form-group" ng-class="{ 'has-error' : userForm.gender.$invalid && userForm.gender.$touched }">
<div class="radio">
<label>
<input type="radio" name="gender" value="male" ng-model="user.gender" ng-required="!user.gender"/>
male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="female" ng-model="user.gender" ng-required="!user.gender"/>
female
</label>
</div>
<div class="help-block" ng-messages="userForm.gender.$error" ng-if="userForm.gender.$touched">
<div ng-messages-include="messages.html"></div>
</div>
</div>
The ngBlur directive resolves the issue that a check boxes list become "touched" only when all the items in list are blurred, calling doTouched() function::
$scope.doTouched = function() {
$scope.userForm.subscribe.$setTouched();
}
P.S. pay attention to correct names: userForm is the HTML name of the <form>, user is the name of the model to which is bound the form.
Here is an example I created that suites our purpose.
Our app would create multiple checkbox questions per page, and $touched didn't seem to work on input checkbox fields that all had the same name attribute.
Also the custom angular plugins/directives I've seen for checkboxes are nice (where they just bind to 1 array model) but don't seem to support 'required'.
Here i set a custom_touched event per question which I set via ng-click:
http://jsfiddle.net/armyofda12mnkeys/9gLndp5y/7/
<li ng-repeat="choice in currentquestion.choices">
<input
type="checkbox"
ng-model="choice.selected"
ng-required="!somethingSelectedInTheGroup(currentquestion.required, currentquestion.choices)"
ng-click="currentquestion.custom_touched = true;"
name="{{currentquestion.question_code}}"
id="{{currentquestion.question_code}}_{{choice.option_value}}"
value="{{choice.option_value}}"
/> {{choice.orig_option_txt}}
</li>
$scope.somethingSelectedInTheGroup = function (is_required, choices) {
if(is_required) {
for(var i = 0; i < choices.length; i++) {
var choice = choices [i];
if(choice.selected) {
return true;
}
}
return false;
} else {
return false;
}
}
Note: i originally had used <div ng-if="questionform.$dirty && questionform[currentquestion2.question_code].$invalid">
but that doesn't work out for multiple checkbox questions per form/page.

Cannot clear form

I am trying to reset the form after the submit button is clicked. I understand that setting the form to pristine alone should not clear the input fields. I tried implementing the various suggestions to clear form by setting the form to pristine and then assigning null to all input fields. Is there a more neat way to implement it ?
Template:
<p>{{contactForm.$pristine}}</p>
<div class="inBox">
<form name="contactForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.email.$invalid && !contactForm.email.$pristine }">
<label>Email</label>
<input type="email" ng-model="tabVm.email" name="email" class="form-control" required>
<p ng-show="contactForm.email.$invalid && !contactForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<div class="form-group">
<label>Contact Number</label>
<input type="tel" ng-model="tabVm.number" class="form-control">
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.message.$invalid && !contactForm.message.$pristine }">
<label>Message</label>
<textarea type="text" rows="5" ng-model="tabVm.message" name="message" class="form-control textBox" required></textarea>
<p ng-show="contactForm.message.$invalid && !contactForm.message.$pristine" class="help-block">Brief message is required.</p>
</div>
</form>
<button type="submit" ng-click="sendMsg()" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >Send</button>
</div>
app.js
$scope.contactForm.$setPristine();
and I also tried
$scope.contactForm.$pristine=true;
Neither of them seem to work. I use angular 1.4.8.
Thank you.
You should use $setPristine() and then reset the ng-model object. Also pay attention you have the submit button outside the <form>.
This is a working JSFiddle (I used only one input for example)
$scope.sendMsg = function() {
$scope.contactForm.$setPristine();
$scope.tabVm = {};
}
You referenced controlForm, but the html you posted have contactForm
I finally got it working by making the following changes :
<div class="container box col-lg-6" >
<p>{{contactForm.$pristine}}</p>
<p>name state: {{contactForm.name.$pristine}}</p>
<div class="inBox">
<form name="contactForm" ng-submit="sendMsg(contactForm)" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<input type="submit" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >
</form>
</div>
</div>
and app.js :
$scope.sendMsg=function(form){
if(form.$valid){
console.log("Form is valid"); //this was a check I used to confirm that the controller recognized the form.
}
form.$setPristine();
tabVm.name="";
}
}
I do not clearly understand why this works or what was I doing wrong earlier. I would appreciate if anyone could explain. Thank you.
Do as follows
$scope.sendMsg = function(){
//your function code
$scope.tabVm={};
$scope.tabVm.name='';
$scope.tabVm.email='';
$scope.tabVm.number='';
$scope.tabVm.message='';
}

How to validate a combo box in ionic framework

I am creating a mobile app using ionic framework.
I have a form which I have created for my hybrid mobile application..
I need to check whether the user has filled all the fields in the form..
my code...
<ion-view view-title="Request">
<ion-content>
<form novalidate>
<div class="list">
<label class="item item-input item-select">
<div class="input-label">
Request Type:
</div>
<select>
<option selected>--Please select--</option>
<option>Car Pass Ticket</option>
<option>Seminar Pass</option>
<option>Identy Card</option>
</select>
</label>
<label class="item item-input">
<textarea placeholder="Description" name="description" ng-minlength="20" required ></textarea>
</label>
<br/>
<!-- <div class="padding">
<button class="button button-positive" ng-click="submit(description)">
Submit
</button>
</div> -->
<div class="padding">
<button class="button button-positive" ng-disabled="request.$invalid" ng-click="submit(description)">
Submit
</button>
</div>
</div>
</form>
</ion-content>
</ion-view>
Can some one kindly help me to validate the combo-box..
any kind of help is highly appreciated......
This should work
<form name="register_form" ng-submit="submitDetails(user)" novalidate="">
<div class="list">
<label class="item item-input item-floating-label" style="position:relative;">
<span class="input-label">First Name</span>
<input type="text" name="user_first_name" placeholder="First Name" ng-model="user.firstName" ng-required="true">
<p ng-show="register_form.user_first_name.$invalid && !register_form.user_first_name.$pristine" class="help-block">You name is required.</p>
</label>
<!--omitted-->
<input type="submit" class="button button-royal" value="register">
</div>
</form>
Form name is register_form,
<form name="register_form" ng-submit="submitDetails(user)" novalidate="">
Input name is user_first_name,
<input type="text" name="user_first_name" placeholder="First Name" ng-model="user.firstName" ng-required="true">
So validation must pass through those fields
<p ng-show="register_form.user_first_name.$invalid && !register_form.user_first_name.$pristine" class="help-block">You name is required.</p>
Model itself doesn't have $invalid or $pristine properties, so it doesn't make sense
For phone field
<input type="number" name="user_phone" placeholder="Phone No" ng-model="user.phone" ng-minlength="10" ng-maxlength="10" ng-required="true">
<span class="help-block" ng-show="register_form.user_phone.$error.required || register_form.user_phone.$error.number">Valid phone number is required</span>
<span class="help-block" ng-show="((register_form.user_phone.$error.minlength || register_form.user_phone.$error.maxlength) && register_form.user_phone.$dirty) ">phone number should be 10 digits</span>
Try this:
1) Give name attribute to your form
<form name="myForm" novalidate>
2) declare the request types inside of your scope like this:
$scope.requestType = [
{ code: "carPass", name: "Car Pass Ticket" },
{ code: "seminarPass", name: "Seminar Pass" },
{ code: "identityCard", name: "Identy Card"}
];
3) declare select box like this:
<select name="requestType" ng-model="request" required
ng-options="request.code as request.name for request in requestType" >
<option value="">--Please select--</option>
</select>
4) Inside submit method check for $valid attribute of form.
$scope.submit1 = function(description){
if($scope.myForm.$valid){
// Do your stuff
}else{
// Do your stuff
}
}

Using angular submit button causes redirect instead of calling function in SharePoint

I have a form within my angular app (within SharePoint) that uses routing via hashbang, but when I click on a button in my form, it redirects to the root (like it can't resolve the URL so it uses the otherwise setting in my config), instead of executing the function.
Here is the HTML (my controller is defined in the routing):
<form name="newItem" class="form-horizontal" data-ng-submit="createItem()">
<fieldset>
<div class="form-group">
<label class="col-lg-2 control-label" for="itemtype">Type *</label>
<div class="col-lg-10">
<select class="form-control" id="itemtype" data-ng-model="selectedType"
data-ng-options="opt as opt.label for opt in types" required>
<option style="display:none" value="">Select a type</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="title">Title *</label>
<div class="col-lg-10">
<input class="form-control" name="title" id="title" type="text" data-ng-model="itemtitle" placeholder="Add your title (Limited to 70 characters)" data-ng-maxlength="70" required>
({{70 - newItem.title.$viewValue.length}} Characters Remaining)
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="body">Body *</label>
<div class="col-lg-10">
<textarea class="form-control" name="body" id="body" data-ng-model="itembody" rows="4" placeholder="Add your body (Limited to 500 characters)" data-ng-maxlength="500" required> </textarea>
Your summary will be displayed as follows ({{500 - newItem.body.$viewValue.length}} Characters Remaining):<br /> {{itembody}}
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" data-ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" data-ng-click="newItem">Submit</button>
</div>
</div>
</fieldset>
</form>
Here is my controller:
appControllers.controller('appItemPostCtrl', ['$scope', '$location', 'appItems', 'appTypes', function ($scope, $location, appItems, appTypes) {
var itemEntry = new appItems;
console.log(itemEntry);
$scope.types = [];
appTypes.query(function (typedata) {
var itemTypes = typedata.value;
// Foreach type, push values into types array
angular.forEach(itemTypes, function (typevalue, typekey) {
$scope.types.push({
label: typevalue.Title,
value: typevalue.Title,
});
})
});
$scope.createItem = function () {
itemEntry.Title = $scope.itemtitle;
itemEntry.$save();
}
$scope.cancel = function () {
}
}]);
UPDATE: It appears that this is related to SharePoint (My Angular Form is in SharePoint), as even setting the button type to submit as follows triggers the refresh instead of running the function. SharePoint is wrapping everything in a form since it inherits from the Master page of the Web, so when I added two "Angular Forms" to the page, the first angular form was closing the tag on the SharePoint form so the second was able to work. Does anyone have a stable workaround (beyond creating a custom masterpage). Image as follows:
I solved it by closing the tag of SharePoint instead of creating a custom masterpage. Ex:
<!-- Close the default form tag put in place by SharePoint instead of creating a custom Masterpage without this element that requires increased permissions and complexity to deploy. Without this tag closed, the form below will not render properly -->
</form>
<div>
<form id="newItemForm" class="form-horizontal" data-ng-submit="createItem()">
<div class="form-group">
<label class="col-lg-2 control-label" for="itemtype">Type *</label>
<div class="col-lg-10">
<select class="form-control" id="itemtype" data-ng-model="selectedType"
data-ng-options="opt as opt.label for opt in types" required>
<option style="display:none" value="">Select a type</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="title">Title *</label>
<div class="col-lg-10">
<input class="form-control" name="title" id="title" type="text" data-ng-model="itemtitle" placeholder="Add your title (Limited to 70 characters)" data-ng-maxlength="70" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="body">Body *</label>
<div class="col-lg-10">
<textarea class="form-control" name="body" id="body" data-ng-model="itembody" rows="4" placeholder="Add your body (Limited to 500 characters)" data-ng-maxlength="500" required> </textarea>
</div>
</div>
<div class="col-lg-10 col-lg-offset-2">
<!--<button type="button" class="btn btn-default" data-ng-click="cancel()">Cancel</button>-->
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Add type='button' to the buttons. I had this same problem before and assumed it was an angular bug of some kind.
Do both buttons exhibit this behavior or just the Submit button?
The submit button calls newItem from ng-click, but the name of the function in the js is actually createItem.

Resources