D.B D.B - 6 months ago 677
AngularJS Question

Validate a form using Angular-material

How Can I validate a form using Angular-material, I need to functionalities:
1) When click submit show error messages if required fields are empty.
2) Do not send post request(avoid submit) if form fields are not valid.
The next code avoid submit but it does not show error messages when clicking, only when cursor is going out of each input field.

<form name="userForm">
<md-input-container>
<input name="email" placeholder="Email" data-ng-model="vm.registerUserData.email" required />
<div ng-messages="userForm.email.$error" ng-if='userForm.myControl.$dirty'>
<div ng-message="required">This is required!</div>
</div>
</md-input-container>

<md-input-container>
<input name="Password" placeholder="Password" data-ng-model="vm.registerUserData.password" required />
<div ng-messages="userForm.Password.$error">
<div ng-message="required">This is required!</div>
</div>
</md-input-container>

<md-input-container>
<md-button id="registerUser" value="Register" class="md-raised md-primary" ng-click="userForm.$valid && vm.registerUser()" aria-label="login" ng-disabled="login.loginForm.$invalid()">
Create
</md-button>
</md-input-container>
</form>

Answer

You're missing 2 things.

First: add type="submit" to your md-button element.

Second: add novalidate to your form element.

You should also consider using ng-submit on the form element instead of using ng-click on the button.

<form name="userForm" novalidate ng-submit="userForm.$valid &&  vm.registerUser()">
    <md-input-container>
        <input name="email" placeholder="Email" data-ng-model="vm.registerUserData.email" required />
        <div ng-messages="userForm.email.$error" ng-if='userForm.myControl.$dirty'>
            <div ng-message="required">This is required!</div>
        </div>
    </md-input-container>

    <md-input-container>
        <input name="Password" placeholder="Password" data-ng-model="vm.registerUserData.password" required />
        <div ng-messages="userForm.Password.$error">
            <div ng-message="required">This is required!</div>
        </div>
    </md-input-container>                             

    <md-input-container>
        <md-button type="submit" id="registerUser" value="Register" class="md-raised md-primary" aria-label="login" ng-disabled="login.loginForm.$invalid()">
            Create
        </md-button>
    </md-input-container>
</form>
Comments