Wayne Li Wayne Li - 6 months ago 15
AngularJS Question

ng-show with form validation formname.inputname.$error failed

I am learning angularjs and used ng-show with form validation, but it doesn't work. I applied form's name.input's name.$error && !form's name.input's name.$pristine to my error message span but it just failed and no error message output. I also tried to see the value of user_form.username.$pristine and nothing happens. No error message shown on console. Can you please help me find the reason?

<form id="user_form" name="user_form" ng-submit="register()" novalidate>
<table>
<tr>
<td class="area">
<div class="area">
<select>
<option value="">Area</option>
<option value="Australia">+61</option>
</select>
</div>
</td>
<td>
<div class="mobile">
<span><input name="mobileNum" id="mobileNum" type="text" placeholder="Your Mobile Number" class="mobile" ng-model="user.mobile" ></span>
</div>
<span ng-show="user_form.mobileNum.$error.required && !user_form.mobileNum.$pristine">Mobile number is required</span>
</td>
</tr>
<tr>
<td colspan="2">
<span class="name"><input type="name" name="username" placeholder="Your Name" class="name" ng-model="user.name"></span>
<span ng-show="user_form.username.$error.required && !user_form.username.$pristine">Mobile number is required</span>
{{user_form.username.$pristine}}
</td>
</tr>
<tr>
<td colspan="2"><span class="passward"><input type="password" placeholder="Passward" class="pw" ng-model="user.password"></span></td>
</tr>
<tr>
<td colspan="2" class="terms">
<form action="#" method="post">
<input type="checkbox" name="agree" value="1" class="terms" id="check-box">
<label for="check-box"><a target="new" href="pdf/Terms_and_conditions_16may2016.pdf">Terms And Conditions</a></label>
</form>
</td>
</tr>
<tr class="create">
<td colspan="2"><span><input type="submit" value="Create A New Account" class="create" ng-disabled="user_form.$invalid"></span></td>
</tr>
</table>
</form>



Answer

You should add required for it.

Change:

<input name="mobileNum" id="mobileNum" type="text" placeholder="Your Mobile Number" class="mobile" ng-model="user.mobile" >

To:

<input name="mobileNum" id="mobileNum" type="text" placeholder="Your Mobile Number" class="mobile" ng-model="user.mobile" required>

Apply for all inputs.

Comments