简体   繁体   中英

Validate a form before it goes to ng-submit in Angular

I have a form which is wrapped like so:

<form ng-submit="processForm()">
...
        <div class="btn-group" role="group" ng-hide=0>
          <button type="button" value="dog" class="btn btn-default" ng-click="formData.type='dog' ">Dog</button>
          <button type="button" value="cat" class="btn btn-default" ng-click="formData.type='cat' ">Cat</button>
        </div>
...

So one thing I have to do is run a quick check before submitting the form, to make sure that the person has clicked one of those 2 buttons. I can stick this code inside my processForm code, but I feel like it would be nicer to be able to just do a quick validation inside the html file and leave the processForm to not handle visually displaying this error and whatnot. Is there a way or am I wrong?

I would recommend using radio buttons for that. Also there is an error variable given by angular. With mixing these things and html5, you can simply create good validation for this. Without need to submit that to functions.

    <form ng-submit="processForm()" name="form">
    ...
    <div class="input-group">
      <span class="input-group-addon">
          <input type="radio" name="type" ng-model="type" value="dog" required>  Dog <br/>
      </span>
      <span class="input-group-addon">
          <input type="radio" name="type" ng-model="type" value="cat" required>  Cat <br/>
      </span>
    </div>
    <div ng-show="form.name.$error.required">
    Please select one.
    </div>

Here is something about it.

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