Accessing and validating form elements
Contact forms are an important element of any website web application. Without contact forms or other forms, it is difficult to communicate, collect leads, and information online. JavaScript webpages provide several ways for Internet users to interact with forms. Internet users can access and fill in form elements located on a website, read, analyse, or modify values stored in the form, and finally, online forms validate all filled form information before submitting it to the server.

So, let’s understand more about forms in JavaScript.
- Accessing form elements in a website webpage.
- Validating online form elements.
- Using validation in HTML5 forms.
- Managing form submissions in a website.
Accessing form elements in JavaScript.
JavaScript web developers can access and control any webpage form elements using multiple methods, primarily using the getElementById(), getElementsByName(), querySelector(), or querySelectorAll() JavaScript function methods.
Accessing an entire form in JavaScript.
JavaScript web developers can manage a complete form by using the ID or other selector methods of the form element used in a webpage or website.
<form id=”sampleForm”>
<input type=”text” id=”employeename” name=”employeename” required />
<input type=”password” id=”password” name=”password” required />
<button type=”submit”>Submit Form </button>
</form>
const form = document.getElementById(‘sampleForm’);
Accessing form elements by ID in a JavaScript webpage.
JavaScript web developers can manage multiple webpage form elements by their ID attributes.
const employeename = document.getElementById(’employeename’);
const password = document.getElementById(‘password’);
Accessing form elements by name in a JavaScript webpage.
JavaScript web developers can use the name attributes feature to manage and access form elements in a webpage.
const employeename = document.getElementsByName(’employeename’)[0];
const password = document.getElementsByName(‘password’)[0];
Remember, getElementsByName() returns a NodeList value, so the user is indicated the element by its index (e.g., [0]).
Accessing form elements with query selector in JavaScript web page.
To allow Internet users to manage JavaScript form elements with more flexibility, Internet users can use the querySelector() and querySelectorAll() functions.
const employeename = document.querySelector(‘#employeename’);
const password = document.querySelector(‘[name=”password”]’);
Here, the querySelector() function allows more complex selectors such as class, form ID, or special values.
Validating form elements in JavaScript web page.
Validation of forms created in JavaScript web pages can be done manually in JavaScript by testing the values of form elements before submitting the form to the server, or Web developers can use Internet users HTML5 markup language scripts to follow validation attributes.
JavaScript HTML5 built-in form validation.
JavaScript, the HTML5 scripting markup language in web development, provides users with built-in features for form validation, such as required, minimum length, maximum length, pattern, type, and placeholder, etc.
<form id=”sampleForm”>
<input type=”text” id=”employeename” name=”employeename” required minlength=”7″ placeholder=”employeename” />
<input type=”password” id=”password” name=”password” required minlength=”12″ />
<button type=”submit”>Submit Form</button>
</form>
It validates the form in an automatic order before submitting it to the web browser, and displays an error message if the form conditions are not met, such as empty fields or too short input. For this, the user does not need JavaScript programming, but here JavaScript allows the user to customize the form validation process.
Custom validation in JavaScript webpage.
If the user wants to validate a custom form in a website webpage, or wants to add additional form testing features, then the user can use JavaScript to validate the elements present in the form before submitting the form.
Test whether a form field is empty or not in JavaScript form Example.
const form = document.getElementById(‘sampleForm’);
form.addEventListener(‘submit’, function (event) {
const employeename = document.getElementById(’employeename’).value;
const password = document.getElementById(‘password’).value;
// here we use the Custom validation features to check if fields are empty or fill
if (employeename === ” || password === ”) {
event.preventDefault(); //here we Prevent form for submission
alert(‘here you ready to fill above fields.’);
}
});
In this example, it tests whether the Employee Name and Employee Password fields are empty before allowing the form to be submitted. If the form validation process fails, event.preventDefault() stops the form from being submitted.
Validating password on a form example with regular expressions.
JavaScript web developers can use regular expressions to validate more complex requirements, such as ensuring that a password is at least 12 characters long and must contain a combination of letters and numeric special characters.
form.addEventListener(‘submit’, function (event) {
const password = document.getElementById(‘password’).value;
// here we use Password regex at least one letter, one number, and special character 12+ characters
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{12,}$/;
if (!passwordPattern.test(password)) {
event.preventDefault(); // it used to Prevent form submission
alert(‘you should be insert a password 12 character with small capital letter or special character.’);
}
});
Form Validation in HTML5 Markup Script.
HTML5 provides native form validation features in JavaScript web development, which work in automatic order without the need for additional JavaScript program source code.
Common HTML5 attributes in forms.
- Required – This essentially makes existing form fields mandatory.
- Pattern – This validates the inputs in the form against a regular expression.
- MinimumLength and MaximumLength – This determines whether the inputs should be within the form specified length.
- Type – This determines whether the form inputs have a special type, e.g. email, URL address.
Example of JavaScript built-in HTML5 validation.
<form id=”sampleForm”>
<input type=”email” id=”email” name=”email” required placeholder=”Email” />
<input type=”text” id=”employeename” name=”employeename” required minlength=”7″ />
<button type=”submit”>Submit Form</button>
</form>
Here the internet user tries to submit the form, here the web browser tests the related elements.
Here the email field in the form must be a valued email address.
The employee name field must be at least 7 characters long.
Managing form submission in JavaScript.
Once the JavaScript form is validated, the Internet user can manage the form data in multiple orders, such as through Ajax programming, grant permission to submit the form, or stop the form submission.
Form submission process with JavaScript validation.
In this example, if all the form fields are valid, the user grants permission for form submission, or else the user can stop it.
form.addEventListener(‘submit’, function (event) {
const employeename = document.getElementById(’employeename’).value;
const password = document.getElementById(‘password’).value;
// here we use Custom validation to check if fields are empty or not
if (employeename === ” || password === ”) {
event.preventDefault(); // it use to Prevent form submission
alert(‘here you need to fill both form field.’);
} else {
alert(‘your Form data submitted successfully’);
}
});
If the form validation is successful here, then the form is automatically submitted in order. Also, it displays an alert message and stops the form submission process.
Accessing Form Values in JavaScript After Form Submission.
Once the form is submitted in a JavaScript webpage, users can access the values of form elements using the formData, elements, or individual form values properties.
Accessing form data with JavaScript FormData.
const formData = new FormData(form);
formData.forEach((value, key) => {
console.log(key, value); // here is key = field name, value = field value assign form element
});
This approach provides the user with easy access to all form data, which is especially useful when submitting forms via Ajax.
Accessing individual field values in a JavaScript form.
const employeename = form.elements[’employeename’].value;
const password = form.elements[‘password’].value;
Here the form.elements object is a collection of all form fields, which the user can access by their name attributes.
Summary of accessing and validating form elements.
- Accessing form elements – JavaScript developers can manage and access form elements using the getElementById(), getElementsByName(), querySelector(), and querySelectorAll() function methods.
- Validating form elements – JavaScript uses JavaScript programming for custom form validation in web pages and relies on HTML5 form element attributes such as required, minimum length, maximum length, and pattern in form fields for built-in form element validation.
- Handling form submission – If form validation fails in a web page, users can apply the event.preventDefault() function method to prevent form submission, and manage form data as needed.
- HTML5 validation – The HTML5 markup language provides automatic form validation features for many common form fields, such as text input, email, and password.