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

为君一笑 提交于 2020-02-06 04:07:12

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/38446956/angular-2-with-parsley-js-validation-cant-block-the-submit-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!