rey
rey

Reputation: 21

Required tag in input field is not working in Angular html file?

Every time I submit the form, even when the input text fields are empty, the form gets submitted even though I put the required tag. Is there a problem with my code? I don't know how to fix this or where the error lies. Also, how can I clear the input fields after I submit. Thank you in advance. Is it a problem from the compiler (I'm using VS code and I'm launching the website on google chrome)

<div class="row">
    <div class="col-xs-12">
        <form>
            <div class="row">
                <div class="col-sm-5 form-group">
                    <label for="firstName">First Name</label>
                    <input 
                    type="text" 
                    id="firstName" 
                    class="form-control" 
                    #fnameinput
                    required />
                </div>
                <div class="col-sm-5 form-group">
                    <label for="lastName">Last Name</label>
                    <input 
                    type="text" 
                    id="lastName" 
                    class="form-control" 
                    #lnameinput
                    required />
                </div>
                <div class="col-sm-5 form-group">
                    <label for="phone">Phone Number</label>
                    <input 
                    type="text" 
                    id="lname" 
                    class="form-control" 
                    #phoneinput
                    required />

                </div>
                <div class="col-sm-2">
                    <button 
                    class="btn btn-success" 
                    type="submit" 
                    (click)="onAddContactItem()"
                    >Add New Contact</button>
                </div>
            </div>
        </form>

    </div>
</div>

form {
    /* Just to center the form on the page */
    margin: 0 auto;
    width: 400px;
    /* To see the outline of the form */
    padding: 1em;
    border: 3px solid #CCC;
    border-radius: 1em;
  }


  label {
    /* To make sure that all labels have the same size and are properly aligned */
    display: inline-block;
    width: 90px;
    text-align: center;
  }

  button {
    /* This extra margin represent roughly the same space as the space
       between the labels and their text fields */
     font-size: 16px;
     display:block;
     border: 0;           
     height: 34px;
     margin: 0;         
     float:left;
  }

  input:invalid {
    border: 2px dashed red;
  }

  input:valid {
    border: 2px solid black;
  }

Upvotes: 1

Views: 221

Answers (1)

Aypn
Aypn

Reputation: 349

novalidate is default in later version of angular. So HTML5 validators are not triggered. Use ngNativeValidate in your form as an attribute ( )

Upvotes: 1

Related Questions