Keywords: AngularJS | form validation | red border
Abstract: This paper explores a technical solution for displaying red borders on all invalid fields after form submission in AngularJS. By analyzing the problem background and limitations of simple CSS selectors, it details the core approach using ng-class to dynamically add classes combined with CSS, with references to ng-submitted as an optimization. The article rewrites code examples to illustrate key concepts through step-by-step explanations, suitable for technical blog or paper style.
Problem Background
In AngularJS applications, form validation is a common requirement, often leveraging HTML5 attributes such as required and type="email". However, when users submit the form without filling required fields or with incorrect formats, it is necessary to display red borders after submission to highlight errors, rather than in the initial or dirty state. This leads to issues where CSS selectors like input.ng-invalid show borders as soon as the form opens, affecting user experience.
Core Solution
Based on the best answer, the solution involves using the ng-class directive to dynamically add a class, such as submitted, upon form submission. This can be implemented on the form element or input fields. Example code:
<form name="addRelation" ng-class="{submitted: addRelation.submitted}">
<input type="text" name="FirstName" required />
</form>
In the AngularJS controller, set $scope.addRelation.submitted = true when the form is invalid. This results in the form element gaining class="submitted". Then, apply red borders using the CSS selector form.submitted .ng-invalid:
form.submitted .ng-invalid {
border: 1px solid #f00;
}
This approach adheres to AngularJS validation mechanisms, displaying borders only after submission to avoid initial interference.
Optimization and Supplement
Referencing other answers, AngularJS automatically adds the ng-submitted class to forms upon submission, which can be directly utilized without manual setup. For instance, use the selector form.ng-submitted .ng-invalid. This method simplifies code but requires ensuring the form element has a name attribute to enable validation.
Implementation Steps
- In HTML, add
ng-classto the form or rely onng-submitted. - In the AngularJS controller, define a
savefunction that sets asubmittedflag when the form is invalid. - In CSS, define appropriate selectors to apply border styles.
Conclusion
The solution presented in this paper effectively addresses the issue of showing red borders on invalid fields after form submission in AngularJS by combining ng-class with CSS. It avoids initial disruptions and can be optimized using ng-submitted. This method is applicable to various validation scenarios, enhancing user experience and code maintainability.