How to prevent form submission when input validation fails in AngularJS ?
Last Updated :
25 Jul, 2024
Validation of fields is an important process while developing a dynamic web application. In terms of security, validation is an important concept. We pass the data from the client side through input fields to the server. If any of the fields is not validated properly and the user sends any irrelevant data then there can be cause of different security attack. So before submitting any of the forms in AngularJS, the validation of the fields should be done. We can validate the fields by setting the regex expressions, character limits, and more validations.
In this article, we will see how we can prevent form submission when input validation fails in AngularJS.
The below steps will be followed to configure the AngularJS Application:
Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir form-validate
cd form-validate
Step 2: Create the index.html file which will have the entire behavior of the application including the styling, AngularJS code, and structural HTML code.
We will understand the above-mentioned approaches through the illustration.
Using AngularJS Built-in Validation
In this approach, we are using the AngularJS built-in validation utilities. Here, we are validating the Username, Email, and Mobile Number fields. We have used the inbuilt validation fields like, required, ng-minlength, ng-pattern, placeholder, etc to provide the validation to the fields.
Below is the detailed information on the inbuilt validations used:
- Username Field
- required: This makes sure that the username field is required and must not be submitted empty
- ng-minlength="3": This defines a minimum length of 3 characters for the username field.
- Email Field
- required: Make sure that the email field is required and must not be left empty.
- ng-pattern="/^.+@.+\..+$/": Uses a regular expression pattern to check if the entered email address has a valid format.
- Mobile Number Field
- ng-pattern="/^[0-9]{10}$/": Uses a regular expression pattern to validate that the mobile number consists of exactly 10 digits.
- placeholder: Provides a placeholder to guide users on the expected format.
Example: Below is an example that showcases the preventing form submission when input validation fails in AngularJS using AngularJS Built-in Validation.
HTML
<!DOCTYPE html>
<html ng-app="formApp">
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
}
.container {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
width: 400px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: green;
}
h3 {
color: rgb(0, 0, 0);
}
form {
margin-top: 20px;
}
.form-group {
margin: 10px 0;
}
label {
display: block;
text-align: left;
margin-bottom: 5px;
font-weight: bold;
}
input {
width: 90%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
input.ng-invalid {
border-color: #f00;
}
.error {
color: #f00;
font-size: 14px;
text-align: left;
}
button {
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
button:hover {
background-color: #2e87d3;
}
</style>
</head>
<body ng-controller="formController">
<div class="container">
<h1>GeeksforGeeks</h1>
<h3>
Approach 1: Using AngularJS Built-in Validation
</h3>
<form name="myForm"
ng-submit="submitForm()" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text"
id="username"
name="username"
ng-model="user.username" required
ng-minlength="3">
<span class="error"
ng-show="myForm.username.$dirty">
<span ng-show="myForm.username.$error.required">
Username is required.</span>
<span ng-show="myForm.username.$error.minlength">
Username must be at least 3 characters long.
</span>
</span>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email"
id="email"
name="email"
ng-model="user.email" required
ng-pattern="/^.+@.+\..+$/">
<span class="error" ng-show="myForm.email.$dirty">
<span ng-show="myForm.email.$error.required">
Email is required.
</span>
<span ng-show="myForm.email.$error.pattern">
Invalid email address.
</span>
</span>
</div>
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="tel"
id="mobile"
name="mobile"
ng-model="user.mobile"
ng-pattern="/^[0-9]{10}$/"
placeholder="Enter 10-digit mobile number" required>
<span class="error"
ng-show="myForm.mobile.$dirty">
<span ng-show="myForm.mobile.$error.required">
Mobile number is required.
</span>
<span ng-show="myForm.mobile.$error.pattern">
Please enter a valid
10-digit mobile number.
</span>
</span>
</div>
<button type="submit"
ng-disabled="myForm.$invalid">
Submit
</button>
</form>
<div ng-show="submitted">
<h2>Form submitted successfully!</h2>
</div>
</div>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<script>
var app = angular.module('formApp', []);
app.controller('formController', function ($scope) {
$scope.user = {};
$scope.submitted = false;
$scope.submitForm = function () {
if ($scope.myForm.$valid) {
alert('Form submitted successfully!');
$scope.submitted = true;
}
};
});
</script>
</body>
</html>
Output:
Using Custom Controller-Based Validation
In this approach, rather than relying on the inbuilt validation utilities, we have defined our own custom controller-based validation functions. Here, for each field of Username, Password, and Confirm Password, we have used the custom controller function.
Below is the explanation of the custom controllers used:
- validateUsername(): This checks the minimum length of 5 characters for the username field. If it is not satisfied then the error message is been displayed dynamically.
- validatePassword(): This checks whether the entered password by the user is at least 8 characters long. If not, then the error message is been shown and the form is not submitted till the input is as per the validation.
- validateConfirmPassword(): This is used to validate the Confirm Password field. This checks whether the password entered here is the same as the Password field above.
Example: Below is an example that demonstrates the preventing form submission when input validation fails in AngularJS using Custom Controller-Based Validation.
HTML
<!DOCTYPE html>
<html ng-app="formApp">
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
}
.container {
background-color: #f4f4f4;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
width: 400px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: green;
}
h3 {
color: rgb(0, 0, 0);
}
form {
margin-top: 20px;
}
.form-group {
margin: 10px 0;
}
label {
display: block;
text-align: left;
margin-bottom: 5px;
font-weight: bold;
}
input {
width: 90%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
.error {
color: #f00;
font-size: 14px;
text-align: left;
}
button {
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
button:hover {
background-color: #2e87d3;
}
</style>
</head>
<body ng-controller="formController">
<div class="container">
<h1>GeeksforGeeks</h1>
<h3>
Approach 2: Using Custom Controller-Based Validation
</h3>
<form name="myForm"
ng-submit="submitForm()" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text"
id="username"
name="username"
ng-model="user.username"
ng-change="validateUsername()" required>
<span class="error"
ng-show="usernameError">
{{ usernameError }}
</span>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password"
id="password"
name="password"
ng-model="user.password"
ng-change="validatePassword()" required>
<span class="error"
ng-show="passwordError">
{{ passwordError }}
</span>
</div>
<div class="form-group">
<label for="confirmPassword">
Confirm Password:
</label>
<input type="password"
id="confirmPassword"
name="confirmPassword"
ng-model="user.confirmPassword"
ng-change="validateConfirmPassword()" required>
<span class="error"
ng-show="confirmPasswordError">
{{ confirmPasswordError }}
</span>
</div>
<button type="submit"
ng-disabled="formInvalid">
Register
</button>
</form>
</div>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<script>
var app = angular.module('formApp', []);
app.controller('formController', function ($scope) {
$scope.user = {};
$scope.usernameError = '';
$scope.passwordError = '';
$scope.confirmPasswordError = '';
$scope.formInvalid = true;
$scope.submitForm = function () {
if (!$scope.usernameError && !$scope.passwordError
&& !$scope.confirmPasswordError) {
alert('Registration successful!');
}
};
$scope.validateUsername = function () {
$scope.usernameError = '';
if (!$scope.user.username) {
$scope.usernameError = 'Username is required.';
} else if ($scope.user.username.length < 5) {
$scope.usernameError =
'Username must be at least 5 characters long.';
}
$scope.validateForm();
};
$scope.validatePassword = function () {
$scope.passwordError = '';
if (!$scope.user.password) {
$scope.passwordError =
'Password is required.';
} else if ($scope.user.password.length < 8) {
$scope.passwordError =
'Password must be at least 8 characters long.';
}
$scope.validateConfirmPassword();
};
$scope.validateConfirmPassword = function () {
$scope.confirmPasswordError = '';
if (!$scope.user.confirmPassword) {
$scope.confirmPasswordError =
'Confirm Password is required.';
} else if (
$scope.user.confirmPassword !== $scope.user.password) {
$scope.confirmPasswordError =
'Passwords do not match.';
}
$scope.validateForm();
};
$scope.validateForm = function () {
$scope.formInvalid =
!!$scope.usernameError || !!$scope.passwordError
|| !!$scope.confirmPasswordError;
};
});
</script>
</body>
</html>
Output:
Similar Reads
How to prevent duplicate submission in a form using jQuery?
Preventing duplicate submission in a form using jQuery involves implementing measures to ensure that the form is only submitted once, regardless of how many times the user interacts with the submit button. To prevent duplicate form submissions in web applications using jQuery we can use various meth
4 min read
How to perform custom validation in Angular forms?
Angular's built-in form controls provide a set of predefined validators for common validation such as required fields, email format, and minimum/maximum values. However, there may be cases where you need to implement custom validation logic specific to your application's requirements. Angular offers
4 min read
How to get form input value using AngularJS ?
Given a form element and the task is to get the form values input by the user with the help of AngularJS. Approach: We are storing the data in the JSON object after the user enters it in the input element with the help of the Angular.copy(object) method. After that, data from the JSON object can be
2 min read
How to set the input field value dynamically in AngularJS ?
Given an input field and the task is to set the input field value dynamically with the help of AngularJS. Approach: A value is being set to the input field despite the user enter something or not. ng-click event is used to call a function that sets the value to 'This is GeeksForGeeks' with the help
2 min read
How to submit form on pressing Enter with Angular 9?
To submit a form in angular we have the following options: Create a button to submit the form.Assign a key to submit the formOr we can do both. In this tutorial, we will see how to use a specific key(Enter in this case) to submit a form. Approach: We can use angular keydown event to use Enter key as
2 min read
How To Validate Input Field In The HTML Form?
Input fields are essential components of HTML forms, enabling users to provide data for processing. Ensuring proper validation of these input fields enhances user experience and prevents errors or malicious inputs. What We Are Going to Create?We will create simple Validating Input Fields in HTML For
3 min read
How to check whether a form or a control is valid or not in Angular 10 ?
In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid or not. Syntax: form.valid Return Value: boolean: the boolean value to check whether a form is valid or not. NgModule: Module used by the
1 min read
How to Reset an Input Value when Limit Exceeds using AngularJS ?
The task is to handle an input field if the number entered by the user in the input exceeds some limit using angularJS. We define a limitTo directive and use it on an HTML input element. This directive is used for all the handling of overflowing limits. The directive calls a function on the keypress
2 min read
How to clear form after submission in Angular 2?
In Angular 2, they are two types of forms: Template-driven forms. Reactive forms. In template-driven forms, most of the content will be populated in .html file.In Reactive forms, most of the functionalities and content will be performed in .ts file. The main advantage of reactive forms is, we can cr
2 min read
How to Prevent Buttons from Submitting Forms in HTML?
We will use different approaches for preventing buttons from submitting forms. There are several reasons where preventing the buttons from submitting forms, i.e., if the user hasn't completed all the required form fields, or added incorrect details in the form, etc. Below are the approaches to preve
3 min read