Troopers
Troopers

Reputation: 5452

How to use ng-required with $touched?

I try to set an input as required if another input has changed. My need is to require confirm password if password has changed.

I use this on the input of confirm password but it is never required :

ng-required="userForm.Password.$touched"

CodePen

Another question : Is there a way to remove ng-Model="user.ConfirmPassword"? because ConfirmPassword is not necessary on my model "user", isn't it?

Upvotes: 1

Views: 1625

Answers (2)

Rakesh Chand
Rakesh Chand

Reputation: 3113

You are not using name property, so you can't use form properties for Password and ConfirmPassword...
Also change AND to OR..

here is updated code

<form name="userForm" ng-controller="userController">
  <label for="Password">Set a password:</label>
  <input type="password" name="Password" id="Password" ng-model="user.Password" required />
  <span class="error" ng-show="userForm.Password.$touched">Password is required</span>
  <br />
  <label for="ConfirmPassword">Confirm the password:</label>
  <input name="ConfirmPassword" type="password" id="ConfirmPassword" ng-model="user.ConfirmPassword" ng-required="userForm.Password.$touched" />
  <span class="error" ng-show="userForm.Password.$touched || userForm.ConfirmPassword.$touched || userForm.ConfirmPassword.$error.required">Confirm password is required</span>
  <br/>
  <span>Password: {{user.Password}}</span>
  <br/>
  <span>Conform Password: {{user.ConfirmPassword}}</span>
</form>

Upvotes: 1

Oliver Salzburg
Oliver Salzburg

Reputation: 22099

You should use the name property instead of id.

Also, this is no valid syntax:

<span class="error" ng-show="userForm.Password.$touched  userForm.Password.$error.required">Password is required</span>

It should be:

<span class="error" ng-show="userForm.Password.$touched">Password is required</span>

Then it will work just fine, as long as Password is the name of the input element, not the ID.

Upvotes: 2

Related Questions