I'm trying to use angular js validations in my form, but for some reasons it is not working properly, please take a look at my code :
<table class="table table-hover table-bordered">
<form name="editPercentageForm" id="editPercentageForm" novalidate>
<thead>
<tr>
<th>From Hours</th>
<th>To Hours</th>
<th>Percentage</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cancellationPercentData in cancellationPercent">
<td class="form-group">
<input type="number" name="editFromHours" ng-model="cancellationPercentData.fromHours" class="form-control" ng-disabled="disableField" id="{{ $index }}fromHours" required/>
<p ng-show="editPercentageForm.editFromHours.$touched && editPercentageForm.editFromHours.$invalid">This field is required</p>
<td class="form-group">
<input type="number" name="edittoHours" ng-model="cancellationPercentData.toHours" class="form-control" ng-disabled="disableField" id="{{ $index }}toHours" required/>
<p ng-show="editPercentageForm.edittoHours.$touched && editPercentageForm.edittoHours.$invalid">This field is required</p>
<p ng-show="edittoHours>=editFromHours" class="text-danger">To Hours should not be more than to Hours</p>
</td>
<td class="form-group">
<input type="text" name="editPer" ng-model="cancellationPercentData.percentage" class="form-control" ng-disabled="disableField" id="{{ $index }}percentage" required/>
<p ng-show="editPercentageForm.editPer.$touched && editPercentageForm.editPer.$invalid">This field is required</p>
</td>
<td class="form-group">
<button class="btn btn-success col-xs-12" type="button" ng-click="disableField = false" ng-show="disableField" style="margin-bottom: 1%;">Edit</button>
<button class="btn btn-success col-xs-12" type="submit" style="margin-bottom: 1%;" ng-disabled="editPercentageForm.$invalid" ng-click="updateCancellations(cancellationPercentData, $index+'fromHours', $index+'toHours', $index+'percentage')" ng-show="disableField == false">Update</button>
<button class="btn btn-primary col-xs-12" type="button" ng-click="deleteCancellations(cancellationPercentData)" style="margin-bottom: 1%;">Delete</button>
</td>
</tr>
</tbody>
</form>
</table>
Thank you in advance :)
答案 0 :(得分:1)
Don't submit the form on Button Click. Do it on ng-submit in form tag. This will not let the form to submit until its completely validated.
Moreover, the approach can be better than this one. You should make one form per line.
This means that your form should be in ng-repeat
too.
This wouldn't let the your form to get submitted without being validated.
Another approach can be by calling a validate function inside the function definition of your updateCancellations()
function.
If the the custom validation function returns false, just return the execution from there, else let it execute to finish.
答案 1 :(得分:1)
You have to submit the form as ng-submit at form line instead of button, ng-repeat should be on form level. This will work all your validate the fields.