Javascript Form Validering med Pristine
Posted on November 30, 2024 (Last modified on May 26, 2025) • 2 min read • 379 wordsVideo is in Swedish
Form validation is an essential aspect of web development, ensuring that user input meets specific requirements before submitting it to the server. In this article, we’ll explore how to validate forms using JavaScript and Pristine, a popular library for form validation.
Pristine is a lightweight JavaScript library designed specifically for form validation. It provides an easy-to-use API for validating forms, making it a great choice for developers who want to simplify their form validation process.
To get started with Pristine, you’ll need to include the library in your HTML file:
<script src="pristine.min.js"></script>
Next, create a form element and add the data-pristine
attribute to it:
<form id="myForm" data-pristine>
<!-- Form fields go here -->
</form>
To validate your form using Pristine, you’ll need to create a validation function that checks for specific conditions. For example, let’s say we want to validate a username field to ensure it contains only letters and numbers:
const myForm = document.getElementById('myForm');
const pristine = new Pristine(myForm);
pristine.addWriter('username', (username) => {
return /^[a-zA-Z0-9]+$/.test(username);
});
In this example, we create a Pristine
instance and add a writer function for the username
field. The writer function checks if the input value matches the regular expression /^[a-zA-Z0-9]+$/
, which ensures that only letters and numbers are allowed.
While Pristine provides an easy-to-use API, you can also validate forms using pure JavaScript. Here’s an example of how to do it:
const myForm = document.getElementById('myForm');
const usernameField = myForm.querySelector('#username');
usernameField.addEventListener('input', () => {
const usernameValue = usernameField.value;
if (!/^[a-zA-Z0-9]+$/.test(usernameValue)) {
alert('Invalid username format!');
}
});
In this example, we add an event listener to the username
field that checks the input value on each key press. If the value doesn’t match the regular expression, it alerts the user with an error message.
Validating forms is a crucial aspect of web development, and Pristine provides a simple way to do it. By using Pristine or pure JavaScript, you can ensure that your forms are validated correctly, providing a better user experience for your visitors. Whether you’re building a complex form or a simple one, Pristine and JavaScript have got you covered!
Swedish