简体   繁体   中英

Prevent angular form from submitting if input is blank

I have an Angular form inside a ng2 popup:

<popup>
  Sign up for our Newsletter!     <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button>         <input type="email"/>
      <button>Submit</button>
    </form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>

here is the onClick event function:

constructor(private popup:Popup) { }
  testAlert() {   ClickButton(){
    alert("Newsletter event works");    this.popup.options = {
  widthProsentage: 15,
  showButtons: false,
  header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
  }   

It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty

I tried using RegEx but it did not work

Consider adding validation.

Something like this:

      <div class="form-group row">
        <label class="col-md-2 col-form-label"
               for="userNameId">User Name</label>
        <div class="col-md-8">
          <input class="form-control"
                 id="userNameId"
                 type="text"
                 placeholder="User Name (required)"
                 required
                 (ngModel)="userName"
                 name="userName"
                 #userNameVar="ngModel"
                 [ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
          <span class="invalid-feedback">
            <span *ngIf="userNameVar.errors?.required">
              User name is required.
            </span>
          </span>
        </div>
      </div>

You can then disable the submit button if the fields are not valid:

         <button class="btn btn-primary"
                  type="submit"
                  style="width:80px;margin-right:10px"
                  [disabled]="!loginForm.valid">
            Log In
          </button>

(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission. Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.

Please provide live demo so we can see the whole file (.ts particularly). Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).

See more about proper ngForm usage in official documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM