Validating form on submit in angular - angularjs

Hello i am trying to make my validation display on form submit but validation does not work, form gets sent anyway. This is my form:
<form class="form-horizontal col-md-10" role="form" name="authenticationForm" ng-controller="AuthenticationController as authentication" ng-submit="authenticate(authenticationForm.$valid)" novalidate>
<hr>
<br>
<div class="form-group" ng-class="{ 'has-error' : authenticationForm.email.$invalid && !authenticationForm.email.$pristine && submitted }">
<div class="col-md-4">
<label for="email">Email: </label>
</div>
<div class="col-md-6">
<input type="email" id="email" name="email" ng-model="email" class="form-control" ng-required/>
<p ng-show="authenticationForm.email.$invalid && !authenticationForm.email.$pristine && submitted" class="help-block">
Your email address is required.
</p>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : authenticationForm.password.$invalid && !authenticationForm.password.$pristine && submitted }">
<div class="col-md-4">
<label for="password">Password</label>
</div>
<div class="col-md-6">
<input type="password" id="password" name="password" ng-model="password" class="form-control" ng-required/>
<p ng-show="authenticationForm.password.$invalid && !authenticationForm.password.$pristine && submitted" class="help-block">
Password is required.
</p>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<span class="help-block errorMessages" ng-show="user.input.errors !== undefined">
<div class="alert alert-danger">
<ul class="list">
<li ng-repeat="error in user.input.errors">
<i class="fa fa-times"></i> <% error %>
</li>
</ul>
</div>
</span>
<div class="form-group">
<div class="col-md-12">
<br/>
<hr>
<button class="big-red-button" type="submit">Login <i class="glyphicon glyphicon-chevron-right"></i></button>
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
</form>
This is my controller function:
$scope.authenticate = function(isValid) {
// settting submitted to true
$scope.submitted = true;
// check to make sure the form is completely valid
if (isValid) {
var req = {
method: 'POST',
url: '/auth/login',
headers: {
'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
},
data: {
email: $scope.email,
password: $scope.password
}
}
$http(req)
.success(function (data, status, headers, config) {
if (data.url !== undefined)
{
window.location.href = data.url;
}
})
.error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
//alert(data);
});
}
};
Can someone please point out what i am doing wrong here? Thanks. :)

You should be able to check $scope.authenticationForm.$valid and prevent the xhr, and you can also visually set the submit button to ng-disabled="authenticationForm.$invalid" so they can't click the button until it's valid. That disabled setting won't prevent submitting the form other ways (enter key, etc).
Have you checked the boolean coming to you? It should be false is there's a validation error.

As you are using controllerAs syntax then you should use each ng-model as
authentication.email & authentication.password
Email Field
<input type="email" id="email" name="email" ng-model="authentication.email"
class="form-control" ng-required/>
Password Field
<input type="password" id="password" name="password" ng-model="authentication.password"
class="form-control" ng-required/>
then inside controller you could get this value by this.email & this.password

That happened to me too. Change ng-required to required, make sure the isValid boolean is actually false if it's not a valid form and take out the novalidate in the form element.
Sometimes the angular $valid is not always accurate. Also, I think you should have put ng-required="true" or some function that returns true, if you are using ng-required.
Check out this article: http://arnaldocapo.com/blog/post/detect-if-html-5-validation-ui-is-present/53

Just replace every where ng-required to required like:
<input type="text" required/>
and also set ng-controller="AuthenticationController " instead of
ng-controller="AuthenticationController as authentication"

Related

AngularJS validation Error after Submitting and data clearing

I have implemented validation system in forms and it working fine.
Here is my form:
<form name='addContactForm'>
<div class="form-group">
<label for="userid">USER ID :</label><br>
<input ng-model="formModel.userid" class="form-control" name="userid" restrict-input="{type: 'digitsOnly'}" required>
<span style="color:red" ng-show="addContactForm.userid.$dirty && addContactForm.userid.$invalid">
<span ng-show="addContactForm.userid.$error.required"> User is required.</span>
<span ng-show="addContactForm.userid.$error.number">Invalid userID</span>
</div>
<div class="form-group">
<label for="name">NAME :</label><br>
<input ng-model="formModel.name" class="form-control" name="name" required/>
<span style="color:red" ng-show="addContactForm.name.$dirty && addContactForm.name.$invalid">
<span ng-show="addContactForm.name.$error.required"> Name is required.</span>
<span ng-show="addContactForm.name.$error.lettersOnly">Invalid Name</span>
</span>
</div>
<div class="form-group">
<label for="email">Email :</label> <br>
<input type="email" name="email" class="form-control" ng-model="formModel.email" ng-pattern="/[\w\d\.\_]+\#[\w\d]+\.[\w]{3}/" required>
<span style="color:red" ng-show="addContactForm.email.$dirty && addContactForm.email.$invalid">
<span ng-show="addContactForm.email.$error.required">Email is required.</span>
<span ng-show="addContactForm.email.$error.pattern">Invalid email address.</span>
</span>
</div>
<div class="form-group">
<label for="phone">Phone :</label> <br>
<input ng-model="formModel.phone" class="form-control" name="phone" restrict-input="{type: 'digitsOnly'}" required>
<span style="color:red" ng-show="addContactForm.phone.$dirty && addContactForm.phone.$invalid">
<span ng-show="addContactForm.phone.$error.required"> Phone Number is required.</span>
</span>
</div>
<div class="row justify-content-center">
<button class="btn btn-primary" ng-disabled="addContactForm.$invalid" ng-click="PassDataToDisplyThroughUrl()">Submit</button> <br>
</div>
</form>
</div>
Note that, above things are working fine.
my controller is below:
app.controller('formCtrl', ['$scope', '$location', '$http',
function($scope, $location, $http) {
$scope.formModel = {};
$scope.PassDataToDisplyThroughUrl = function() {
var url = 'display/' + $scope.formModel.userid + '/' + $scope.formModel.name
+ '/' + $scope.formModel.email + '/' + $scope.formModel.phone;
$location.path(url);
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
.then(function(response){
$scope.successCallBack = 'You have successfully saved your contact';
}, function(response){
$scope.errorCallBack = 'Opps! Unable to save your data, please check your network';
});
$scope.formModel = {};
$scope.addContactForm.$setPristine();
};
}]);
After i clicking on submit button -- it clear the form and send to the server. but the problem is, it shows me the validation error later
Can anyone fix me this issue?

How to display error message when passwords doesn't match in Angularjs?

I'm new at Angularjs and my question is how to display an error message when the password doesn't match with confirm password?
Can someone help me, this is not very difficult but I'm still learning to programme.
Thanks to everyone!
I have html code:
<form ng-submit="saveItem(userForm.$valid)" name="userForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control" required ng-model="activeItem.username" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordString" />
</div>
<div class="form-group">
<label for="password">Confirm Password</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordConfirm" />
</div>
<p ng-show="(userForm.passwordConfirm != '') && (userForm.password != userForm.passwordConfirm)">Passwords don't match</p>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control" required id="username" ng-model="activeItem.name" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
And angular function:
$scope.saveItem = function(){
console.log($scope.activeItem);
//delete $scope.activeItem.hash_method
var objectToSave = {
username: $scope.activeItem.username,
//password: $scope.activeItem.password,
name: $scope.activeItem.name,
id: $scope.activeItem.id
};
if($scope.activeItem.passwordString != ''){
if($scope.activeItem.passwordString == $scope.activeItem.passwordConfirm){
objectToSave.password = $scope.activeItem.passwordString;
} else {
console.log('Confirm password error');
}
}
You'll want to keep different Id's for the two password fields, also take a look at your model bindings:
<input type="text" class="form-control" id="password" ng-model="activeItem.passwordString" />
<input type="text" class="form-control" id="passwordConfirm" ng-model="activeItem.passwordConfirm" />
You can just reference the items that are bound with ng-model within an ng-if/ng-show, and then you shouldn't need any custom logic on the back-end.
<p ng-show="(activeItem.passwordString && activeItem.passwordConfirm) && activeItem.passwordString
!== activeItem.passwordConfirm ">Passwords don't match</p>
Also, you'll probably want to use '!==' over '!=' since you're just comparing two strings, as it's more strict of a comparison.
Edit: one thing to note, with this direction you'll still probably want to do error checking in the save function, but this should handle displaying the error message without any issues.
Remember the operator for 'not equal' is "!==", with that you will be able to make it!

Clear form input field after submit in Angularjs with php..? [duplicate]

This question already has answers here:
Resetting form after submit in Angularjs
(5 answers)
Closed 4 years ago.
When i am click add button for add records in next time then last form data is present in form it is not clear in bootstrap form model.
$scope.saveAdd = function () {
$http({
method: 'post',
url: 'user/insert',
data: $scope.form,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data)
{
if (data == 1) {
$scope.user_succ = $scope.user_succ ? false : true;
$scope.succ = "User added successfully";
$timeout(function () {
$(".modal").modal("hide");
}, 3000);
} else if(data == 3) {
$scope.confirm_password=$scope.confirm_password ? false :true;
$scope.confirm_password_error="Confirm Password is Not Matched";
}else{
$scope.user_err = $scope.user_err ? false : true;
$scope.err = "User insertion failed! Try again.";
}
});
};
My View page:-
This is my view page that is load from angularjs routes.js.If you found any error error please give me some feedback.or any others angularjs validation you have please share with me.
<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
<div class="modal-body">
<div class="form-group">
<label for="name" class="col-form-label">Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.name" id="name" name="name" placeholder="Enter Name" required>
<span style="color:red" ng-show="addItem.name.$touched && addItem.name.$invalid">Please Enter User Name.</span>
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.phone" id="phone" name="phone" placeholder="Enter Phone Number" required="">
<span style="color:red" ng-show="addItem.phone.$touched && addItem.phone.$invalid">Please Enter Phone Number.</span>
</div>
<div class="form-group">
<label for="usertype" class="col-form-label">User Type<span class="text-danger">*</span></label>
<select class="form-control" ng-model="form.type" id="type" name="type" required="">
<option value="">Select a user type</option>
<option value="branch">Branch Admin</option>
<option value="manager">Branch Manager</option>
</select>
<span style="color:red" ng-show="addItem.type.$touched && addItem.type.$invalid">Select User Type.</span>
</div>
<div class="form-group">
<label for="address" class="col-form-label">Address</label>
<textarea class="form-control" ng-model="form.address" id="address" name="address" placeholder="Enter Address" required=""></textarea>
<span style="color:red" ng-show="addItem.address.$touched && addItem.address.$invalid">Please Enter Address.</span>
</div>
<div class="form-group">
<label for="username" class="col-form-label">Username<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.username" id="username" name="username" placeholder="Enter Username" required="">
<span style="color:red" ng-show="addItem.username.$touched && addItem.username.$invalid">Please Enter Username.</span>
</div>
<div class="form-group">
<label for="password" class="col-form-label">Password<span class="text-danger">*</span></label>
<input type="password" class="form-control" ng-model="form.password" placeholder="Password" name="password" required="required" ng-minlength="6"/>
<div ng-if="addItem.password.$touched || signupSubmitted">
<p style="color:red" ng-show="addItem.password.$error.required" class="help-block">Password is required</p>
<p style="color:red" ng-show="addItem.password.$error.minlength" class="help-block">Minimum 6 character</p>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Confirm Password<span class="text-danger">*</span></label>
<input type="password" class="form-control" name="confirm_password" ng-model="form.confirm_password" placeholder="Confirm password" match-password="password" required>
<div ng-if="addItem.confirm_password.$touched || signupSubmitted">
<p style="color:red" ng-show="addItem.confirm_password.$error.required" class="help-block">Confirm password is required</p>
<p style="color:red" ng-show="confirm_password" >{{confirm_password_error}}</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>`
You can try reset function which reset your form fields. But this is not the accurate solution. Please provide your Complete controller and HTML code to make an accurate solution.
$scope.resetForm = function(){
/* reset the data to a new object so that all the properties
* of form are reset
*/
$scope.data = {};
};
UPDATE
Based on the partial HTML code, you can try form controller API setPristine: $scope.FORMNAME.$setPristine();
Replace FORMNAME with your form name. Also make note that as your form is binding a model object to your inputs so, you need to take care of clearing those input model as well:
$scope.formData = {};
Hope this will help to solve your point :)
The reason is that your previous value that you bind with model is still there. So, you can do either of 2 things:
Inject $route in controller and do $route.reload() on ng-submit and the route is reloaded.
Reinitialize the model by creating and calling a function which clears the data.Use $scope.formName.$setPristine() if you have validation depending on this pristine state of form
NOTE: $route.reload() will reload your route, so all the changes which have in your controller will be reverted. So choose accordingly.
Its Work.With Minor Change.
$scope.form = {}; // clears input fields
$scope.NameofFormSubmitted.$setPristine();
$scope.NameofFormSubmitted.$setUntouched();
I think what you are looking for is:
$scope.form = {}; // clears input fields
$scope.NameofFormSubmitted.$setPristine();
$scope.NameofFormSubmitted.$setUntouched(); // resets touch events

how to error message on submitting of a from in angular js

I want to show the required error message once the from is submitted but not sure how to do it i am trying as shown below
<div class="controls">
<form name="formx" >
<ul class="form small">
<div class="tag">ID</div>
<input type="text" class="small" name="enrolmentId" ng-model="enrolmentDetail.Id" required="" onkeypress='return !(event.charCode == 32 )'>
<div class="error text-danger" style="position: absolute;margin-left: 120px;" ng-show="formx.enrolmentId.$error.required && (formx.$submitted || formx.enrolmentId.$touched)"><p>Id is required</p></div>
</li>
<li>
<div class="btn" ng-click="saveDetails(enrolmentDetail)" ng-show="formAction=='save'">SAVE</div>
</li>
</ul>
</form>
</div>
here now the error message is shown once we dirty the textbox but i want to show the error message once the form is submitted and if there is required error from should not be submitted
trying used ng-submit but not sure how to do it
Please help by creating a fiddle or posting a example to do it
This is an example
html
<body ng-app="myApp">
<div ng-controller="myCtrl as mc">
<form class="form" name="myForm" ng-submit="mc.submit(myForm)" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input name="username" class="form-control" type="text" ng-model="mc.username" required/>
<p class="text-danger" ng-show="myForm.username.$error.required && mc.submitted">Username is required</p>
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" class="form-control" type="password" ng-model="mc.password" required/>
<p class="text-danger" ng-show="myForm.password.$error.required && mc.submitted">Password is required</p>
</div>
<button class="btn btn-success">submit</button>
</form>
<p class="text-success" ng-show="mc.sent && mc.submitted">Form sent</p>
js
angular.module("myApp",[])
.controller("myCtrl", function(){
var vm = this;
vm.submit = submit;
function submit(form){
vm.submitted = true;
if(form.$valid && vm.submitted === true){
//Send data logic
vm.sent = true;
}
}

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='';
}

Resources