刷新验证码提交表单

时间:2017-12-06 12:56:05

标签: angular angular2-forms captcha

当我尝试刷新验证码时,它会提交表单。我想知道为什么?刷新后,它会将数据发布到数据库并向其添加空注释。似乎没有任何东西似乎只是在向我提交表格。

<form (ngSubmit)="onSubmit(); captcha.reset(true)">

    <h2 *ngIf="!parent.replying">Leave a Comment</h2>
    <h2 *ngIf="parent.replying">Leave a Reply</h2>

    <div class="form-group">
        <textarea class="form-control" name="message" placeholder="Message here" [(ngModel)]="comment.message"></textarea>
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="name" placeholder="Name (Optional)" [(ngModel)]="comment.name" title="Anonymous by default">
    </div>

    <div class="form-group">
        <input type="email" class="form-control" name="email" placeholder="E-mail (Optional)" [(ngModel)]="comment.email">
    </div>

    <math-captcha #captcha></math-captcha>

    <div class="form-group">
        <button type="submit" class="btn btn-warning">Post this comment</button>
        <button *ngIf="parent.replying" type="button" (click)="parent.replying=false" class="btn btn-link">Cancel</button>
    </div>

</form>

验证码组件 -

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'math-captcha',
    template: `
        Give an answer: {{ number1 | in_word }} {{ operation | to_str }} {{ number2 | in_word }} = 

        <input 
            type="text" 
            name="answer" 
            id="answer"
            class="btn btn-default" 
            title="Prove you are human by answering to this math question" 
            placeholder=" ? " 
            [(ngModel)]="user_input" 
            pattern="{{ answer }}"
            size="2" 
            required
        >
        <button 
            (click)="refresh()" 
            class="btn btn-link"
            title="Get Another Math Question"
        ><span 
                class="glyphicon glyphicon-refresh" 
                aria-hidden="true"
            ></span> Refresh</button>

    `
})
export class MathCaptchaComponent implements OnInit {
    user_input: string;
    number1: number;
    number2: number;
    operation: string;
    answer: string;

    ngOnInit() {
        this.number1 = this.random_number();
        this.number2 = this.random_number();
        this.operation = '+'; // for now, only + operation is used
        this.answer = this.number1 + this.number2 + ''; // empty string used to convert number to string
    }

    reset() {
        this.user_input = '';
        this.refresh();
    }

    random_number() {
        return Math.floor((Math.random() * 10) + 1); // multiplication factor 10 is used to get single digit
    }

    refresh() {
        alert("fffff");
        this.ngOnInit();
    }
}

我可以通过更改表单的提交类型来逃避它,但不确定这是否有效。即使它确实如此,为什么上面的表格表现得如此奇怪?

0 个答案:

没有答案