How to validate a Django form using AngularJs? - javascript

My form is very simple. Think of it as having 1 field and one submit button. The validation I want is also quite simple, if the 1 field is empty, then the submit button will be disabled. If not, the submit button will work. I am trying to do this dynamically using AngularJs and not quite sure what I am missing.
Although I am using Django-forms, my form renders in Html like this:
<div ng-app="myApp" ng-controller="searchController">
<form method='POST' action='' class="form-with-blue-labels" name="searchForm">
{% csrf_token %}
<input class="textinput textInput form-control" id="id_professor_name" maxlength="255" name="professor_name" placeholder="Search for a professor" required="required" type="text">
<input ng-disabled="disabled_bool" type="submit" class="btn btn-primary" value="Search" />
</form>
</div>
And my angular file looks like this:
angular.module('myApp', [])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
})
.controller('searchController', [
'$scope', function($scope) {
var search_target = angular.element('#id_professor_name');
if (search_target == ''){
$scope.disabled_bool = true;
}
}
])
Note: Since I am using Django and Angular together in a non-restful way, I changed the angular tags to be {$$}, while Django tags are {{}}.
Any help is appreciated!
EDIT
I have tried this now, and still can't get it to work :/
<div ng-app="myApp" ng-controller="searchController">
<form method='POST' action='' class="form-with-blue-labels" name="searchForm">
{% csrf_token %}
<input ng-change="change()" class="textinput textInput form-control" id="id_professor_name" maxlength="255" name="professor_name" placeholder="Search for a professor" required="required" type="text">
<input ng-disabled="disable_button" type="submit" class="btn btn-primary" value="Search" />
</form>
</div>
using this function
angular.module('myApp', [])
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
})
.controller('searchController', [
'$scope', function($scope){
$scope.change = function(){
if (angular.element('#id_professor_name').length == 0) {
$scope.disable_button = true;
}
else {
$scope.disable_button = false;
}
};
}
])

As suggested here, you need to use ng-disabled="searchForm.$invalid" as you have already set name to required.

Related

Send input text to controller's scope in AngularJS

I have this html page:
<div class="rtm-nav">
<div ng-app>
<body ng-controller="DemandCtrl" ng-submit="submit()">
<label>From:
<input type="text" name="input" ng-model="ctrl.dataa.from">
</label>
<label>To:
<input type="text" name="input" ng-model="ctrl.dataa.to">
</label>
<input type="submit" id="submit" value="Apply" />
<script src="demand/demand.js"></script>
</body>
</div>
</div>
I want to save the input text from the 2 text boxes in the controller's scope. This is how I tried to do it:
class DemandCtrl {
constructor(ChartDataService) {
this.ChartDataService = ChartDataService;
debugger;
this.dataa = {
from: ctrl.dataa.from,
to: ctrl.dataa.to
};
}
$onInit() {
getData.call(null, this);
}
}
I get the error saying:
ReferenceError: ctrl.dataa is not defined
Is any better method to send the data from input text to the controller?
You haven't defined scope which is accepted by your controller. That's why you can't read data from the form. I would also suggest to use <form> to deal with any kind of data submission. So take a look at the refactored example of yours:
==== HTML ======
<div class="rtm-nav">
<div ng-app="my-app">
<form ng-submit="submit()" ng-controller="DemandCtrl">
<label>From:
<input type="text" name="input" ng-model="ctrl.data.from">
</label>
<label>To:
<input type="text" name="input" ng-model="ctrl.data.to">
</label>
<input type="submit" id="submit" value="Apply" />
</form>
</div>
</div>
===== Controller
angular.module('my-app', [])
.controller('DemandCtrl', function($scope) {
$scope.submit = function() {
let data = {
from: $scope.ctrl.data.from,
to: $scope.ctrl.data.to,
}
console.log(data);
};
});

ng-form inside ng-repeat not updating subform.$submitted

I am trying create forms inside ng-repeat, everything is working fine except submit button. Submit button placed in main form it is common for all sub forms.
If the submit button is clicked mainForm.$submitted gets updated but userForm.$submitted dose not changing. Is there any work around for that ?
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.users = [{},{}];
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
main form input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<input type="text" ng-model="user.name" name="name" required>
sub form input valid=>{{userForm.name.$valid}} | sub form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit">Submit</button>
Form valid=>{{mainForm.$valid}} | Main From submit => {{mainForm.$submitted}}
</form>
</div>
Intro
So, I added a ng-click handler to the button so that you set the submitted status of the internal form as well.
The only difficult I had was to actually get the form reference, but I added the function $scope.setUserForm which is called with an ng-init. The solution pattern is from: https://stackoverflow.com/a/23862411/1688441
Also, please keep in mind you need an array of userForms to keep the references. On click you iterate through these elements and set the submitted.
Code
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.UserForms = [];
$scope.setUserForm = function(form) {
$scope.UserForm = form;
$scope.UserForms.push(form);
}
$scope.forms = {};
$scope.users = [{}, {}];
$scope.handleClick = function() {
$scope.UserForms.forEach(function(element) {
element.$submitted = true;
});
};
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<div ng-init="setUserForm(userForm);"></div>
<input type="text" ng-model="user.name" name="name" required>
input valid=>{{userForm.name.$valid}} | form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit" ng-click="handleClick()">Submit</button>
Form valid=>{{mainForm.$valid}} | From submit => {{mainForm.$submitted}}
</form>
</div>

angularjs model value is undefined in form

I have two forms(in one page). On first form there are two buttons NEXT and BACK. On clicking on the next i will render next form on page. I am using ng-if for this condition.
<form name="otpform" novalidate ng-if="renderotpform">
<fieldset ng-disabled="otpdisable">
<div class="middle-container steps fourth-step overflow-hidden" id="divotp">
<input class="" type="text" name="otp" placeholder="{{ 'OTP' | translate }}" ng-model="otp" required >
<input type="button" value="{{ 'BACK' | translate }}" class="brown-button" ng-click="gotoAck()">
<input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="checkotp()">
</div>
</fieldset>
</form>
Below is my js code.
$scope.checkotp = function () {
debugger;
var otpvalue;
$scope.otp = {};
otpvalue = $scope.otp; //undefined
}
When I try to access the otp model I am getting undefined property. On previous form I have next button. Inside next button I have $scope.renderotpform = true; so that above form is shown. May I know why I am not able to access OTP in the above code?
ng-if creates its own scope. So the otp inside ng-if is not binded directly to the controller.You can either bind the model to an object or use controller as syntax. The controller as syntax implicitly takes care of the dot rule.
For more info:
https://github.com/angular/angular.js/wiki/Understanding-Scopes
AngularJs "controller as" syntax - clarification?
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
var vm=this;
vm.renderotpform = true;
vm.checkotp = function() {
console.log(vm.otp);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<form name="otpform" novalidate ng-if="vm.renderotpform">
<fieldset ng-disabled="otpdisable">
<div class="middle-container steps fourth-step overflow-hidden" id="divotp">
<input class="" type="text" name="otp" ng-model="vm.otp" required>
<input type="button" value="BACK" class="brown-button" ng-click="vm.gotoAck()">
<input type="submit" value="NEXT" class="blue-button" ng-click="vm.checkotp()">
</div>
</fieldset>
</form>
</div>
Make all ng-models of the Form from one Object..
It would work and there are other advantages for this like you could easily reset and post data with just one object.:-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.formData = {};
$scope.renderotpform = true;
$scope.checkotp = function() {
console.log($scope.formData.otp);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="otpform" novalidate ng-if="renderotpform">
<fieldset ng-disabled="otpdisable">
<div class="middle-container steps fourth-step overflow-hidden" id="divotp">
<input class="" type="text" name="otp" ng-model="formData.otp" required>
<input type="button" value="BACK" class="brown-button" ng-click="gotoAck()">
<input type="submit" value="NEXT" class="blue-button" ng-click="checkotp()">
</div>
</fieldset>
</form>
</div>

how to check all fields are empty in angularjs

How to check all fields in the submit form ng-submit="submit(field)" is empty in controller.js? They consists of few textboxes and one select field.
I would want an alert box to occur if all fields are empty and select option is not selected, instead of individual validation.
Thanks
While it's not exactly what you're asking about, may be $pristine is what you want? It's a flag on the form indicating whether the form has ever been edited. If someone typed and then cleared out a field, $pristine would still be false, however.
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
</form>
Then in your controller
.controller('FormController', function($scope){
$scope.doSubmit = function(){
if($scope.myform.$pristine){}
}
})
Alternatively, you can set all your fields to required="true" and use the $valid flag on the form in the same way as described above.
You can use this:
ng-show="!yourfield.length"
Something like this:
<form name="yourform">
<input name="yourfield" ng-model="somefield" ng-minlength="10" required>
<span ng-show="!yourfield.myfield.$error.required">Something</span>
</form>
You should look for Form Validation . Take a look at this tutorial.
<input name="name" class="form-control"
ng-model="user.name" placeholder="Name" required>
<div class="alert alert-danger"
ng-show="userForm.name.$error.required">
Please enter the name.
</div>
The following will show an alert if all fields are empty
angular.module('app', [])
.controller('FormController', function($scope) {
$scope.doSubmit = function(){
if (formIsEmpty($scope.myform)){
alert('You forgot to enter something before submitting');
}
};
function formIsEmpty(form) {
for (var prop in form) {
if (!form.hasOwnProperty(prop)) { continue; }
if (prop[0] === '$') { continue; }
if ($scope[prop]) { return false; }
}
return true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
<input ng-model="lastName" name="lastName" />
<textarea ng-model="description" name="description"></textarea>
<button type="submit">Submit</button>
</form>
</div>

Angularjs form not working

I have a form which inputs name of a country and then it overwrites a global variable. Submit button does nothing when clicked. Where am I missing?
Here is the HTML
<div ng-controller="InputController">
<form class="form-wrapper cf" role="form">
<input type="text" ng-model="model.country" placeholder="Search country..." required>
<button type="submit" ng-click="update()">Search</button>
<span>{{model.country}} ======</span>
</form>
</div>
And here is the controller.
LastFmApp.controller('InputController',
function InputController($scope) {
$scope.model = {};
$scope.update = function() {
console.log($scope.model.country);
};
});
I don't think it is an issue with angular js.
The submit button will reload the page so you won't be able to see changes in your model.
You can either use an input type button with ngClick:
<input type="button" ng-click="update()">Search</input >
Or an input type submit with ngSubmit attribute on your form:
<form ng-submit="update()">
<input type="submit">Search</input>
</form>
i dont think there is any issue with your code see your code is working in plunker
<div ng-controller="InputController">
<form class="form-wrapper cf" role="form">
<input type="text" ng-model="model.country" placeholder="Search country..." required>
<button type="submit" ng-click="update()">Search</button>
<span>{{model.country}} ======</span>
</form>
</div>
http://plnkr.co/edit/u9hqu1bASxxMgtEP1qAr?p=preview

Categories

Resources