问题
Form validation is working fine in Firefox but fails in Internet Explorer 9.
I'm having this span tag for the dynamically generated mandatory fields to validate empty fields.
<span ng-show="hasError('"+fieldName+"', 'required')"></span>
$scope.hasError= function(field, validation){
if(validation){
return ('$scope.myForm.field.$dirty' && '$scope.myForm.field.$error[validation]') || ($scope.submitted && '$scope.myForm.field.$error[validation]');
}
return ('$scope.myForm.field.$dirty' && '$scope.myForm.field.$invalid') || ($scope.submitted && '$scope.myForm.field.$invalid');
};
Initailly I had
$scope.hasError = function(field, validation){
if(validation){
return ($scope.myForm[field].$dirty && $scope.myForm[field].$error[validation]) || ($scope.submitted && $scope.myForm[field].$error[validation]);
}
return ($scope.myForm[field].$dirty && $scope.myForm[field].$invalid) || ($scope.submitted && $scope.myForm[field].$invalid);
};
which gave me
TypeError: Unable to get value of the property '$dirty': object is null or undefined
in IE9 console, after changing it to the above posted code, the TypeError is gone but still the red border around the text box to alert the user for empty fields does not come in IE9.
What should be done specific to IE9 so that I can validate the empty fields?
Or is there any other way to validate form fields which are generated dynamically in both Firefox and IE?
回答1:
The best way I know to ensure validation for a form is check that the form is valid on submit.
Following the Developer Guide for Forms, create a function called update. Then add a check to see if the form is valid before saving:
$scope.update = function(user) {
if (!$scope.myformname.$valid) return false;
$scope.master = angular.copy(user);
};
The other important steps are connecting this new update function to the Submit button:
<form ng-submit="update(user)" name="myformname" novalidate>
And in my opinion, disabling the Submit button while the form is invalid:
<input type="submit" ng-disabled="!myformname.$valid" value="Save" />
Please see the following example. I included two different styles of showing error messages.
回答2:
I think it should be $scope.myForm.field.$error.dirty
来源:https://stackoverflow.com/questions/27382799/form-validation-not-working-in-internet-exloprer-9-angularjs