3
votes

I'm learning AngularJS and I've got a problem with validating form inputs on client-side. I've got a REST API in Yii2 and a registration form validates on server side. I would like to add some client-side validation also. Here is the code for one input (for other is pretty much the same):

<form ng-submit="register()" name="registerForm" id="register-form" method="post" role="form" novalidate>
    <div ng-class="{ 'has-success': (!error['login'] && submitted) || (registerForm.login.$touched && registerForm.login.$valid),
    'has-error': (error['login'] && submitted) || (registerForm.login.$touched && registerForm.login.$invalid) }"
     class="form-group">
     <label class="control-label" for="login">Username</label>
     <input ng-model="registrationForm.login" type="text" id="login" class="form-control" name="login" required>
     <p class="help-block help-block-error">{{ error['login'] }}</p>
     <p class="help-block" ng-show="registerForm.login.$invalid && registerForm.login.$touched">This field is required.</p>
</div>
... (other inputs)
</form>

Some explanation: has-success should be set if input is valid - first bracket is for server side validation, second is for client side. - first help-block is displaying server-side validation error - second help-block is displaying client side validation error

The issue: Errors on client-side validation don't display. Also, the whole div class is not setting up.

What am I doing wrong?

EDIT: Added form which is wrapping inputs.

1
First off i believe you are missing the form element in this snippet. Do you have a form which goes by the name of 'registerForm' which wraps the text field? If you do, it is best that you add it to the snippet.asulaiman

1 Answers

0
votes

You are missing the form that encapsulates the input field. Angular validation is done on the form level, you cannot validate stand-alone input fields (unless you use a ng-form directive - https://docs.angularjs.org/api/ng/directive/ngForm). The validation errors appear when you use a form with the correct name associated to your validation.

Validated in this plunk

<div ng-class="{ 'has-success': (!error['login'] && submitted) || (registerForm.login.$touched && registerForm.login.$valid),
'has-error': registerForm.login.$touched && registerForm.login.$invalid }" class="form-group">
<form name="registerForm">
  <label class="control-label" for="login">Username</label>
  <input ng-model="registrationForm.login" type="text" id="login" class="form-control" name="login" required>
</form>
<p class="help-block" ng-show="registerForm.login.$invalid && registerForm.login.$touched">This field is required.</p>