Angular 2 with parsley.js validation can't block the submit button - angularjs

I have questions about submit button. Now I can use the parsley validation in the form and it works perfectly. However, when user clicks submit button which binds with angular, and if there is an invalid input in the form, my app can't stop executing the click function. All the validations then become useless.
I don't want to use the angular built-in validation since parsely.js can handle so many input situations. The following is my codes:
apply-page.ts
import {RouteParams,Router,ROUTER_DIRECTIVES} from '#angular/router-deprecated';
import {Component, ViewEncapsulation} from '#angular/core';
import {Widget} from '../../core/widget/widget';
import {DropzoneDemo} from '../../components/dropzone/dropzone';
import {HolderJs} from '../../components/holderjs/holderjs';
import {NKDatetime} from 'ng2-datetime/ng2-datetime';
import {Autosize} from 'angular2-autosize/angular2-autosize';
import {AlertComponent} from 'ng2-bootstrap/components/alert';
// import models
import {PersonalInfo} from './model/personal-info';
import {Job} from '../model/job';
import {JobService} from '../job-service';
import {NgForm} from '#angular/common';
declare var jQuery: any;
#Component({
directives: [
ROUTER_DIRECTIVES, Widget, DropzoneDemo, HolderJs, NKDatetime, Autosize, AlertComponent,
EducationForm, ExperienceForm
],
selector: '[apply-page]',
host: {
class: 'apply-page app'
},
template: require('./apply-page.html'),
encapsulation: ViewEncapsulation.None,
styles: [require('./apply-page.scss'), require('../login-page.scss'), require('./forms-validation.scss')]
})
export class ApplyPage {
colorOptions: Object = {color: '#f0b518'};
sliderValueOptions: Array<number> = [200, 1547];
personalInfo: PersonalInfo;
extraAddr: string;
job: Job;
constructor(
// the service to get data from mock-data
private jobService: JobService,
private routeParams: RouteParams,
private router:Router
){}
// called only one time at the loading time
ngOnInit(): void {
jQuery('#colorpicker').colorpicker(this.colorOptions);
jQuery('.select2').select2();
jQuery('.js-slider').slider();
jQuery('#markdown').markdown();
jQuery('.selectpicker').selectpicker();
// initialize parsleyjs to validate the input
jQuery('.parsleyjs').parsley();
this.personalInfo = new PersonalInfo();
this.educations = new Array<Education>();
this.experiences = new Array<Experience>();
this.skills = SKILLS;
// fetch the id from url
let id = this.routeParams.get('id');
this.getJob(id);
}
// TODO: submit form to server
onSubmit(){
console.log("on submit");
}
apply-page.html
<form class="parsleyjs" data-parsley-priority-enabled="false" novalidate="novalidate" (ngSubmit)="onSubmit()">
<div class="page-section">
<div class="page-section-part">
<div class="row page-header-row">
<div class="col-md-6 page-sub-title">
PERSONAL INFO
</div>
</div>
<div class="row page-header-row ">
<div class="col-md-6 medium-text" align="center">Do you have a LinkedIn account?</div>
<div class="col-md-6" align="center">
<input type="image" src="assets/images/pictures/linkedin-button.png" class="img-btn" (click)="getLinkedIn()" onClick="return false" alt="..."/>
</div>
</div>
<div class="row page-header-row">
<div class="col-md-8 col-md-offset-3 small-text">We make it easier for you to import your professional profile.</div>
</div>
</div>
<div class="widget-body">
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="form-group">
<label class="page-label" for="first-name">First name</label>
<input [(ngModel)]="personalInfo.firstName" class="form-control" placeholder="First name" id="first-name" type="text" required ngControl="first-name">
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="form-group">
<label class="page-label" for="last-name">Last name</label>
<input [(ngModel)]="personalInfo.lastName" class="form-control" placeholder="Last name" id="last-name" type="text" required ngControl="last-name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="form-group">
<label class="page-label" for="email">Email</label>
<input [(ngModel)]="personalInfo.email" class="form-control" placeholder="email#domain.com" id="email" type="email"
data-parsley-trigger="change"
data-parsley-validation-threshold="1"
required data-parsley-required-message=""
ngControl="email">
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="form-group">
<label class="page-label" for="phone">Phone</label>
<input [(ngModel)]="personalInfo.phone" class="form-control" placeholder="i.e: Sales, Marketing" id="phone" data-parsley-type="number" required data-parsley-required-message="" ngControl="address">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12">
<div class="form-group">
<label class="page-label" for="address">Address</label>
<input [(ngModel)]="personalInfo.address" class="form-control" placeholder="1200 Fulton st, NY, NY 10001" id="address" type="text" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="form-group">
<label class="page-label" for="">Address</label>
<input [(ngModel)]="extraAddr" class="form-control" placeholder="1200 Fulton st" type="text">
</div>
</div>
</div>
</div>
</div>
<div class="form-actions page-section-submit">
<button class="btn btn-danger btn-lg mb-xs" role="button">
Submit your application
</button>
</div>
</form>
The button is at the bottom of the apply-page.html file. When clicking the button is will call the onSubmit() function in apply-page.ts. Really want to know if there is any solution about it. Thank you.

I've found the way to do that. In ngOnInit(), I should get the instance of parsley by:
// initialize parsleyjs to validate the input
this.instance = jQuery('.parsleyjs').parsley();
Then, in the onSubmit() function:
onSubmit(){
if(this.instance.isValid()){
// TODO: submit form to server
}else {
console.log("do nothing");
}
}
I should figure out how to use jQuery and parsley in angular 2 first and then try to implement them on my app. Hope this will help others. Thank you.
By the way, here is good video about how to use jQuery in angular 2. https://www.youtube.com/watch?v=vrdHEBkGAow

I think there's a bug in Parsley, sorry. Specify type="submit" in your button and it should work fine.

Related

using input type with react

I'm write application with react, and I have a issue to use the tag input
enter code here:import React, { Component } from 'react'
enter code here :import { Formik } from 'formik';
enter code here:export class Login extends Component {
render() {
return (
<div class="header">
<div class="container">
<div class="logo"></div>
<div class="form">
<form>
<div class="inputemail">
<label class="labelinput" for="">email or phone</label>
<input class="input" type="text">
<div class="inputpassword">
<label class="labelinput" for="">Password</label>
<input class ="input"value type="password">
<a class="linkpassword" href="#">forget password?</a>
<input class="inputbtn" type="submit" value="entrar">enter</input>
</input>
</div>
</input>
</div>
</form>
</div>
</div>
</div>
)
};
}
export default Login;
when the react don't accept the tag input. someone know why this happen?
First of all, you have to use className="" instead of class="".
Second, You have an unclosed input <input class="input" type="text"> You have to close it first.
And the last part is also inappropriate for react.
<input class="inputbtn" type="submit" value="entrar">enter</input>
</input>
Please clean your HTML firstly. All tags have to be closed. Even such as and
If this doesn't solve the problem, please send us your error.
you have a sintax error in your code and your missing closing tags, use this:
render() {
return (
<div class="header">
<div class="container">
<div class="logo" />
<div class="form">
<form>
<div class="inputemail">
<label class="labelinput" for="">
email or phone
</label>
<input class="input" type="text" />
<div class="inputpassword">
<label class="labelinput" for="">
Password
</label>
<input class="input" value type="password" />
<a class="linkpassword" href="#">
forget password?
</a>
<input class="inputbtn" type="submit" value="enter" />
</div>
</div>
</form>
</div>
</div>
</div>
);
}

not able to get modal data in to angularjs controller

I am trying to add user to database using bootstrap modalI am not getting any error but not able to fetch user data.
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-3 control-label" >First name</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="firstname">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Last name</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="lastname" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" ng-click="add()">Add</button>
</div>
</div>
</form>
</div>
my controller is:
$scope.add = function()
{
console.log(firstname); //here i want to display fn&ln and make http request to codeigniter api o/p in console is: firstname(not the username entered)
}
And i also want to update it in database using codeigniter api call, can anyone plz help me through this?
You should use $scope.firstname you need to have $scope for accessing scope variables
Don't forget to add ng-app and ng-controller to your template HTML

AngularJS Form controller from directive

I am trying to submit a simple contact form. The form is inside a bootstrap modal (don't think that makes any difference) but the controller is in a directive.
The html for the form is as followed:
<form name="contactForm" ng-submit="contactForm()" novalidate>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="text" placeholder="Full name" name="name" ng-minlength="3" max="20"
ng-model="name" id="name" class="form-control">
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="email" ng-minlength="4" placeholder="Email address" name="contactEmail"
ng-model="email" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-md-12 col-sm-12">
<input type="text" ng-model="subject" name="subject" ng-minlength="10" id=""
placeholder="Subject" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-md-12 col-sm-12">
<textarea class="form-control" ng-model="message" name="message" ng-minlength="10"
placeholder="Your message"></textarea>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 col-md-12 col-sm-12">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</div>
</form>
Which i think is all good. The body of my controller looks like this
$rootScope.contactForm = contactForm();
function contactForm() {
console.log('triggered!');
var contactFormVars = {
name: $rootScope.name,
contactEmail: $rootScope.contactEmail,
subject: $rootScope.subject,
message: $rootScope.message
}
// With Promise
Stamplay.Object('contactform')
.save(contactFormVars)
.then(function(res) {
console.log('yes!');
}, function(err) {
console.log('No!');
})
}
return directive;
};
EDIT: Controller now looks like this:
function contactForm($rootScope,$stamplay,$q) {
$rootScope.data = {}
$rootScope.data = {
name: $rootScope.data.name,
contactemail: $rootScope.data.contactemail,
subject: $rootScope.data.subject,
message: $rootScope.data.message
}
Stamplay.Object("contactform")
.save($rootScope.data, function (err, res) {
console.log(res);
console.log(err);
// res is the new car object
});
}
When i click the submit button I get the following error which i've been Googling
Error: v2.contactForm is not a function. (In 'v2.contactForm()', 'v2.contactForm' is an instance of FormController)
fn
Any help with this is appreciated.
EDIT
Ok so now i've moved the js from a directive and placed it in to the main controller. At the moment its not making any difference, only that the error has changed very slightly:
angular.js:12722Error: v4.contactForm is not a function. (In 'v4.contactForm(ensureSafeObject(v5,text))', 'v4.contactForm' is an instance of FormController)
fn
Not sure what the difference between v2 and v4 is.
Any advice to get past this blocker is appreciated.

validate form on button in angularjs

I have to validate a form only after click on button. Now it is working on blur and focus. How can I disable focus and blur validation and validate them on button click. fiddle
<form ng-app="form-example" class="row form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="email" id="inputEmail" placeholder="Email" ng-model="email" required>
<div class="input-help">
<h4>Invalid Email</h4>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input ng-model="password" class="immediate-help" required type="password" id="inputPassword" placeholder="Password">
<div class="input-help">
<ul>
<li>required</strong></li>
</ul>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn">Create Account</button>
</div>
</div>
</form>
You could have dummy class on your form level that will tell the form has been submitted or not like ng-class="{submitted: submitted}", and on click of button we will use ng-click="submitted=true" so that after clicking on button form will have submitted class on it. Then we will apply our CSS rule for ng-invalid & ng-dirty to also consider an .submitted class by using concept of deep nesting of classes.
/* Show red border when stuff has been typed in, but its invalid */
.submitted .ng-dirty.ng-invalid {
border-color:#ec3f41;
}
Other CSS rules should be taken care of this thing like I shown above.
the problem is that you just added the validation and you're showing the message on ng-invalid ( with css). here is an example of working code to do what you want.
<div class="form-group col-xs-12 required" ng-class="{ 'has-error' : creditCardDetailsForm.security_code.$invalid && submitted}">
<label class="col-lg-28 col-l-5 col-md-5 text-left font-l-20 primary control-label">Security code (CVC) </label>
<div class="col-lg-3 col-md-4 text-left">
<input class="form-control" name="security_code" data-stripe="cvc" ng-model="payment_details.security_code" type="number" minLength="3" required>
<p ng-show="creditCardDetailsForm.security_code.$invalid && submitted" class="help-block">Security code is required.</p>
<p ng-show="creditCardDetailsForm.security_code.minLength.$invalid && submitted" class="help-block">Invalid CVC.</p>
</div>
</div>
see, here I check if the form is invalid and the submitted has been clicked...
in my controller:
$scope.purchasePackage = function (status, response) {
$scope.submitted = true;
if ($scope.creditCardForm.creditCardDetailsForm.$valid) {
//do something
}
};
since you did your hide and show with CSS you can just add the class on click to the form and then do .submitted .ng-invalid so it only shows up after you have submitted.

Loading a modal form with data in Angular

Trying to learn Angular ... and
I'm missing something really obvious here, I'm sure of it. However, all of the examples, fiddles or plunkers I'm finding deal with validating create forms, not update forms.
My application is creating a modal form to add/edit client data. If a valid clientId is passed in, the form is opened as an edit and the data is loaded into the form.
When I load the values, I'm only assigning the value to the modal's property. Since its only a value, it doesn't have an $invalid function or any of the other nice form methods. Without that, the validation doesn't work. What's the proper way to load data into a form in Angular so that it can be validated? Thanks!
angular.module('app').controller("clientController",
function ($scope, $modalInstance, dataService, clientId) {
$scope.clientForm = {}
$scope.clientForm.clientId = clientId;
$modalInstance.opened.then(function () {
if (clientId > 0) {
dataService.getClient(clientId).then(function (clientData) {
$scope.clientForm.name = clientData.Name;
$scope.clientForm.address1 = clientData.Address1;
$scope.clientForm.address2 = clientData.Address2;
$scope.clientForm.city = clientData.City;
$scope.clientForm.stateId = clientData.StateId;
$scope.clientForm.zip = clientData.Zip;
$scope.clientForm.email = clientData.Email;
});
};
});
$scope.ok = function () {
$scope.clientForm.$submitted = true;
if ($scope.clientForm.$valid) {
$modalInstance.close($scope.clientForm);
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
)
And for the form:
<script type="text/ng-template" id="ClientEdit.html">
<div class="modal-header">
<h3 class="modal-title"><span>Client</span></h3>
</div>
<div class="modal-body col-md-12">
<form name="clientForm" novalidate>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtclientName">Name: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtclientName" type="text" ng-model="clientForm.name" required /></div>
<p ng-show="clientForm.name.$invalid">Name is required.</p>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtAddressLine1">Address 1: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtAddressLine1" type="text" ng-model="clientForm.address1" /></div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtAddressLine2">Address 2: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtAddressLine2" type="text" ng-model="clientForm.address2" /></div>.
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtCity">City: </label>
<div class="col-md-2"><input class="form-control input-sm" id="txtCity" type="text" ng-model="clientForm.city" /></div>
<label class="col-md-1 control-label text-right" for="txtZip">Zip: </label>
<div class="col-md-2"><input class="form-control input-sm" id="txtZip" type="text" ng-model="clientForm.zip" /></div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtEmail">Email: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtEmail" type="email" ng-model="clientForm.email" /></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()" ng-disabled="clientForm.$invalid">Save</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>

Resources