AngularJS - Create dynamic email fields and checking and validation - angularjs

I would like to create a form with several fields: name, last name, ... and add one or several email. The first email field is mandatory. After he should have the possibility to click on "Add email" for adding a new email address. He could add 4 others emails (5 emails in total).
The system should be verify if the format of the email is correct, display a message if necessary and register the data in a DB.
Here my controler "ctrlAddContacts" and module (app.js):
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap', 'ngDialog']);
app.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError : function(rejection) {
//console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response : function(response) {
//console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array.
//If the intercept param is missing or set to true, we display a modal containing the error
if (typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
app.controller('ctrlAddContacts', function ($scope, ContactService){
$scope.title="Add a contact";
// Allow to create several fields EMAIL
$scope.emails = [
{
}];
$scope.log = function() {
console.log($scope.emails);
};
$scope.add = function() {
var dataObj = {email:''};
$scope.emails.push(dataObj);
}
$scope.submitForm = function(contact){
if($scope.ContactForm.$valid){
// Send the object to the backend for saving data
ContactService.addNewPerson(contact).success(function(Person){
$scope.ContactForm.$setPristine();
$scope.contact= Person;
});
}
}
});
Here my factory (appService.js)
app.factory('ContactService', function($http){
var factory={};
factory.addNewPerson=function(objContact){
//alert(objContact);
return $http.get('http://myapp/contacts.cfc?method=addNewPerson&jsStruct=' + JSON.stringify(objContact))
};
return factory;
})
The function in the backend (server) retrieves the parameter objContact sent by the backend and executes correctly the query (it's working)
Here my view (manageContact.html)
<h3>{{title}}</h3>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">Person Sheet</div>
</div>
<div class="panel-body">
<form name="ContactForm" class="form-horizontal" role="form" novalidate ng-submit="submitForm(contact)">
<div class="form-group">
<label for="txtLastName" class="col-sm-2 control-label">Last Name *</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtLastName" maxlength="100" placeholder="Enter Last Name" required ng-model="contact.LASTNAME">
</div>
</div>
<div class="form-group">
<label for="txtPhone" class="col-sm-2 control-label">Phone Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="txtPhone" maxlength="20" placeholder="Enter phone" ng-model="contact.PHONENUMBER">
</div>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ START --->
<div>
<div ng-repeat="email in emails">
<div class="form-group">
<label for="txtEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="txtEmail_" maxlength="100" placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
</div>
</div>
<button ng-click="add()">Add Email</button>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ END--->
<div class="error-container"
ng-show="ContactForm.txtEmail.$dirty && ContactForm.txtEmail.$invalid">
<small class="error"
ng-show="ContactForm.txtEmail.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.minlength">
Your email is required to be at least 3 characters
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.email">
That is not a valid email. Please input a valid email.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.maxlength">
Your email cannot be longer than 20 characters
</small>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="Submit" ng-disabled="ContactForm.$invalid">
Cancel
</div>
</div>
</form>
</div>
</div>
Could you please help me for doing the difference in the name of the 5 fields: txtEmail_1, txtEmail_2 in the controler and the view (when the new field is created).
Kind Regards,

You could try the following for creating dynamic form element name attributes.
<div class="col-sm-10">
<input type="email" class="form-control"
name="txtEmail_{{$index}}" maxlength="100"
placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
<span ng-show="ContactForm['txtEmail_' + $index].$invalid">Enter a valid email</span>

Related

How does AngularFire $save function work?

I want to update a group of fields based on the contract number input in, user can choose which field they want to change, and can set the value. my code does not change the record, I don't know why.I guess the reason might be the prop is not defined. The app is build on using the api of AngularFire, my code is as follows:
<div class="container-fluid">
<div class="row">
<h3>Contract renewal & Group update other fields</h3>
<form class="form-horizontal" ng-submit="groupUpdate()" name="contractupdateForm">
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Contract Number</label>
<div class="col-sm-8">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter contract number so related fileds could be group updated" ng-model="contractupdate" ng-required="true">
</div>
</div>
</div>
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Fields Category</label>
<div class="col-sm-8">
<div class="input-group">
<select class="form-control" id="productfield" name = "productfield" ng-model="fieldupdate" ng-options="f.value as f.label for f in fields">
<option value="">No filed selected</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Updated value</label>
<div class="col-sm-8">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter value supposed to be changed" ng-model="valueupdate" ng-required="true">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" >
Change group value
</button>
</div>
</div>
</form>
<hr>
</div>
</div>
The controller part is as follows:
$scope.groupUpdate = function(){
console.log($scope.contractupdate);
console.log($scope.fieldupdate);
console.log($scope.valueupdate);
for(var i = 0; i< productsInfo.length;i++){
if(productsInfo[i].productcontract == $scope.contractupdate){
var prop = $scope.fieldupdate;
productsInfo[i].prop = $scope.valueupdate;
productsInfo.$save(i).then(function(ref) {
console.log("group update success");
}, function(error) {
console.log("Error:", error);
});
}
/*if(i.productcontract == $scope.contractupdate){
var field = $scope.fieldupdate;
console.log(productsInfo[i].field);
productsList[i].field == $scope.valueupdate;
productsList.$save().then(function(productRef){
console.log("group updated success");
ref.key === obj.$id; // true
}, function(error) {
console.log("Error:", error);
});
}*/
};
};
The second $save operation needs to be chained from the promise returned from the first $save operation:
var promise = productsInfo.$save().then(function(ref) {
console.log("group update success");
//return to chain ref
return ref;
}, function(error) {
console.log("Error:", error);
//throw to chain error
throw error;
});
var p2 = promise.then(function(ref) {
//do more here
//return to chain promise
return productsInfo.$save();
}).catch(function(error) {
console.log("Error:", error);
//throw to chain error
throw error;
});
var p3 = p2.then(function(secondRef) {
//do even more
When code is put in a function given to a .then method, the $q service waits for the promise to resolves before invoking that function. The .then method returns a derived promise which can be used for further chaining.
For more information, see AngularJS $q Service API Reference -- chaining promises

Connect Express nodemailer with Angular

I'm trying to make a contact form, and the server side is working pretty well. But I don't know how to connect Angular to the html form and send it with Express. Any would appreciate any help.
My Express
router.get('/sendQuote', function(req, res) {
var data = req.query;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
});
So, my html:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
And the main problem is here, how to glue Angular with HTML and Express. I can send emails, but get undefined in the fields of Name, Email and so on. :
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.sendMail = function () {
$scope.message = {};
$http.get('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
I think you should start by making this request a POST and not a GET request.
router.post('/sendQuote', function(req, res) {
var data = req.body;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
res.send(200); // let the client know it sent ok.
});
Now, let's take a look at your Angular code. It seems you want the object $scope.message to hold your form fields data. You should define this as an object at the beginning of your controller.
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.message = {};
$scope.sendMail = function () {
//$scope.message = {}; -- this was clearing the object
$http.post('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// you can clear $scope.message if you want here
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
HTML had one ng-model not binding to the message object:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="message.contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">

How to update data record using angularJS and Laravel?

I'm a beginner and I'm creating a simple CRUD system using AngularJS and Laravel 5. I'm having problems implementing/making the UPDATE feature (to edit data) work. Every time I run it, I keep getting this error on my browser console:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mycrudapp-kkoyao.c9users.io' is therefore not allowed access. The response had HTTP status code 500.*
Here is my code for my html/form:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="addApp" ng-controller="addController">
<h2>Edit Account</h2>
<h4 class="modal-title" id="myModalLabel">Please fill in details</h4>
<div class="modal-body">
<form name="frmAccounts" ng-submit="submitForm(Account.id)" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Account Holder's Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Enter First and Last Name"
ng-model="Account.acctName" ng-required="true">
<span class="help-inline"
ng-show="frmAccounts.name.$invalid && frmAccounts.name.$touched">Name field is required.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctNum" name="acctNum" placeholder="Enter Bank Account Number"
ng-model="Account.acctNum" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctNum.$invalid && frmAccounts.acctNum.$touched">Please check your Bank Account Number.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Type</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctType" name="acctType" placeholder="Savings or Checking Account"
ng-model="Account.acctType" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctType.$invalid && frmAccounts.acctType.$touched">Please indicate bank account type.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Current Balance </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctBalance" name="acctBalance" placeholder="Enter current balance"
ng-model="Account.acctBalance" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctBalance.$invalid && frmAccounts.acctBalance.$touched">Check Bank Account Balance</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btn-save" ng-disabled="frmAccounts.$invalid">Save Account</button>
</div>
</form>
</div>
</div>
<script included here, see below>
</body>
</html>
Then here is my AngularJS script (included in the body tag, below of my html page):
<script>
// Defining angularjs application.
var app = angular.module('addApp', []);
// Controller function and passing $http service and $scope var.
app.controller('addController', function($scope, $location, $http, $log, $window) {
var url = $location.absUrl();
$scope.url = $location.absUrl();
$http.get(url + "/api")
.then(function (response) {$scope.Account = response.data;}); //this part is working
$scope.submitForm = function(id) {
// Posting data to php file
$http({
method : 'POST',
url : 'https://mycrudapp-kkoyao.c9users.io/api/accounts/' + id,
data : $scope.Account,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarrassing. An error has occured. Please check the log for details');
});
});
</script>
The GET Method at the beginning is working fine and the data is fetched and displayed on the forms.
But when I click the "Save" Button to call the submitForm() function in my script, nothing happens and I get the error (see above) on my browser console (Chrome). But this script was edited and came from my CREATE a new entry feature, and was working fine. So I'm not sure what is the problem.
Anyway, here are my Laravel codes:
Laravel Route:
Route::post('/api/accounts/{id}', 'AccountCtrl#update');
Laravel Controller:
public function update(Request $request, $id) {
$account = Account::find($id);
$account->acctName = $request->input('acctName');
$account->acctNum = $request->input('acctNum');
$account->acctType = $request->input('acctType');
$account->acctBalance = $request->input('acctBalance');
$account->save();
}
I think the problem is in my Laravel controller, but not really sure how to fix it.
Also, how do I fix the code for DELETING data?
I'm sorry for this long, messy post, but it is my first time here and I really need help on this. Thank you very much.
Try to add to your web service the next header:
header("Access-Control-Allow-Origin", "*")
This is a CORS problem, probably because your browser is sending a preflight(OPTIONS) request. A quick search: https://github.com/barryvdh/laravel-cors
Edit: The OPTIONS request should return a 200 OK

Validating form on submit in angular

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"

Parsley Remote validation is not preventing form submission

I am using Parsley Remote validation with angularJS..using the async validator with add new user form is working fine, it uses the API and checks if the user name is already existed, and the email as well, if the user name is there it returns a 200 status, which is not equal to 404 and an error message appears.. BUT when submitting the form, if I check the form.isvalid status it returns true, it is only validating the NON remote options. I am stuck there.
here is the web form
<form class="form-horizontal form-label-left" method="post" id="AddUserForm"
data-ui-jq="parsley"
data-parsley-remote
data-parsley-priority-enabled="false"
novalidate="novalidate">
<fieldset>
<legend>
By default validation is started only after at least 3 characters have been input.
</legend>
<div class="form-group">
<label class="control-label col-sm-3" for="basic">User Name</label>
<div class="col-sm-9">
<input type="text" name="userName" class="form-control" data-ng-model="user.userName" value=""
data-parsley-remote
data-parsley-remote-validator='checkusername'
data-parsley-trigger="focusout"
data-parsley-remote-message="User name is already registerd in the system"
required="required" />
<span class="help-block">
Username must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="email">
E-mail
</label>
<div class="col-sm-9">
<input type="email" id="email" name="email" class="form-control" data-ng-model="user.email"
data-parsley-remote
data-parsley-remote-validator='checkemail'
data-parsley-trigger="focusout"
data-parsley-remote-message="Email is already registerd in the system"
required="required" />
<span class="help-block">
Email must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">
Password:
</label>
<div class="col-sm-9">
<input type="password" id="password" name="password" class="form-control mb-sm" data-ng-model="user.password"
data-parsley-trigger="change"
data-parsley-minlength="6"
required="required" />
<input type="password" id="password-r" name="password-r" class="form-control" placeholder="Confrim Password" data-ng-model="user.confirmPassword"
data-parsley-trigger="change"
data-parsley-minlength="6"
data-parsley-equalto="#password"
required="required" />
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" data-ng-click="AddNewUser($event)" class="btn btn-danger btn-rounded pull-right">Validate & Submit</button>
<button type="button" class="btn btn-default btn-rounded">Cancel</button>
</div>
</form>
and this is my async validator:
window.ParsleyExtend = {
asyncValidators: {
checkusername: {
fn: function (xhr) {
console.log($('[name="userName"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckUserName/' //+ $('[name="userName"]').text()
},
checkemail: {
fn: function (xhr) {
console.log($('[name="email"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckEmail/'// + $('[name="email"]').text()
}
}
};
and this is how I validate the form:
$scope.AddNewUser = function ($event) {
$event.preventDefault();
//THis resturns true allways when the remote validation is not valid,, but when other non remote valdiation happens is works fine
$('#AddUserForm').parsley().validate();
//and this if statement resturns true allways even when the remote validation is not valid,, but when other non remote valdiation happens is works fine
if ($('#AddUserForm').parsley().isValid()) {
authService.saveRegistration($scope.user).then(function (response) {
$scope.savedSuccessfully = true;
// $scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
//startTimer();
},
function (response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
just found the answer.. I have to use asyncIsValid() and asyncValidate() along with the normal isValid() and Validate() methods.. so the code will be as follows:
$('#AddUserForm').parsley().asyncValidate();
if($('#AddUserForm').parsley().isValid() && $('#AddUserForm').parsley().isAsyncValid()) {
....}
I first check each field to make sure it is validated, if a field is not validated, my ok variable will be set to false.
Here is some sample code:
$(function() {
var ok;
$('#signup').parsley().on('field:validated', function() {
ok = $('.parsley-error').length === 0;
})
.on('form:submit', function() {
if (ok) return true;
else return false;
});
});
Parsley.addAsyncValidator('checkExists', function(xhr) {
return false === xhr.responseJSON;
}, '/data-management/verify-data?filter=signup');

Resources