0

I am new to Angular2. Trying to implement validation in form. But, it doesn't worked for me. I tried this

<form #f='ngForm' (ngSubmit)="onSubmit(f.form)">
  <md-card>
    <md-card-content>
      <div class="frm-ctrl form-group">
        <label>Phone Number :</label>
        <div class="wpr">
          <div class="icon">
            <i class="fa fa-phone"></i>
          </div>
          <md-input ngModel #phonenumber="ngModel" [(ngModel)]="PersonInfo.phonenumber" name="phonenumber" class="ctrl-wpr__ctrl form-group"
            min-length="4" required></md-input>
          {{phonenumber.errors | json}}
        </div>
      </div>
    </md-card-content>
  </md-card>
</form>

Help me where I am doing wrong.

1 Answer 1

1
<md-input ngModel 
          #phonenumber="ngModel" 
          [(ngModel)]="PersonInfo.phonenumber" 
          name="phonenumber" class="ctrl-wpr__ctrl form-group"
          min-length="4" required></md-input>

change this to

<md-input #phonenumber="ngModel"              //<<<===removed ngModel
         [(ngModel)]="PersonInfo.phonenumber" 
          name="phonenumber" 
          class="ctrl-wpr__ctrl form-group"
          min-length="4" required></md-input>

To display error msg you can use this code,

<div [hidden]="phonenumber.valid || phonenumber.untouched" class="alert alert-danger">
      phonenumber is required
</div>
Sign up to request clarification or add additional context in comments.

7 Comments

thanks for reply. I want to display an error message below to that textbox.
I tried as you said, but it is not working. It is not showing up error message
What you need to do is, you type in something in md-input and erase it completely (make it blank), you'll have an error msg. (I'm not sure if its not working with md-input, but it should work with <input type=text>). If it doesn't work please replace md-input by <input type=text> to check whether it works with input type=text.
Yeah it's working as you said. But, without typing anything and Tab out it has display error message.
remove || phonenumber.pristine part.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.