JavaScript Form Validation - Validating URLs and Numbers


Form validation is an essential part of web development, ensuring that user inputs are accurate and meet specific criteria. In this guide, we'll focus on validating URLs and numbers using JavaScript and provide examples to demonstrate the validation process.


Validating URLs


URL validation ensures that user-provided URLs are correctly formatted. JavaScript provides regular expressions and methods for URL validation.


Using Regular Expressions


Here's how you can validate a URL using a regular expression:


function isValidURL(url) {
const pattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return pattern.test(url);
}
// Example usage:
const url1 = "https://www.example.com";
const url2 = "invalid-url";
console.log(isValidURL(url1)); // Outputs: true
console.log(isValidURL(url2)); // Outputs: false

The regular expression pattern ensures that the URL starts with "http://" or "https://" (or "ftp://"), followed by valid characters.


Validating Numbers


Number validation ensures that user-provided inputs are valid numbers. JavaScript provides methods to check if a value is a valid number.


Using JavaScript's isNaN Function


Here's how you can validate a number using the isNaN function:


function isNumber(value) {
return !isNaN(value) && isFinite(value);
}
// Example usage:
const num1 = 42;
const num2 = "not a number";
console.log(isNumber(num1)); // Outputs: true
console.log(isNumber(num2)); // Outputs: false

The isNaN function checks if the value is not NaN (Not-a-Number) and is finite, ensuring it's a valid number.


Combining Validation


For form validation, you can combine URL and number validation based on the type of user input. For example, you can validate a URL in one input field and a number in another.


const urlInput = "https://www.example.com";
const numberInput = "42";
if (isValidURL(urlInput) && isNumber(numberInput)) {
// Both inputs are valid
console.log("Form is valid");
} else {
// At least one input is invalid
console.log("Form is invalid");
}

This code snippet checks if both the URL and number inputs are valid and logs the appropriate message based on the result.


Conclusion


Form validation is crucial for maintaining data integrity and ensuring a smooth user experience. JavaScript provides tools like regular expressions and built-in functions to validate various types of input, including URLs and numbers. Effective validation enhances the quality and security of your web applications.


Happy coding with form validation!