When designing web forms, ensuring data integrity is crucial. A common problem is preventing users from including links in certain input fields, such as text areas for descriptions or comments. In this article, we’ll explore how to restrict link in html form using jQuery and regular expressions, weaving the keyword “restrict link in html form” into the content.
Table of Contents
Why limit links?
To prevent potential security risks, spam, or unwanted content, it is often necessary to restrict links in HTML forms. By implementing appropriate validation, you can enhance the user experience and maintain data integrity.
Solution: jQuery and regular expressions
To achieve this, we can use jQuery, a fast and feature-rich JavaScript library. The provided code snippet uses jQuery to validate the contents of the text area with ID description_job in the form with ID form_online_quote. Let’s break down the code and understand how it works.
Restrict Links in HTML Form
Breaking Down the Code
1. Document Ready Function
$(document).ready(function() { /* ... */ });
This ensures that the code within it executes when the DOM is fully loaded.
2. Form Submission Event
$('#form_online_quote').submit(function(event) { /* ... */ });
This code binds a function to the form’s submit event.
3. URL Validation
var urlPattern = /^(?!.*(?:youtube\.com|youtu\.be))(?:(?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9-]+\.[a-z]{2,}(?:\/\S*)?$/;
if (urlPattern.test(textareaValue)) { /* ... */ }
The regular expression urlPattern
ensures that the textarea value does not contain YouTube links. If a link is detected, an error message is displayed, and form submission is prevented.
4. Special Character Validation
var specialCharPattern = /[\'^£$%&*()}{@#~><>|=_+¬]/;
if (specialCharPattern.test(textareaValue)) { /* ... */ }
This checks for the presence of special characters. If found, the same error message is displayed, and form submission is prevented.
5. Displaying Error Message
$('#textarea_error').css('display', 'block');
This line controls the visibility of the error message.
6. Hide Error Message on Validation
$('#textarea_error').css('display', 'none');
If both validations pass, the error message is hidden.
7. Returning Form Submission Status
return true;
If all validations pass, the form is submitted; otherwise, submission is halted.
By integrating this code into your HTML form, you can effectively restrict links and maintain the desired content in your textarea.
Output Preview:
Conclusion
I hope this article helped you to learn How to restrict link in html form. If you have any doubts or problem with the code, comment below to find the solutions. Also share this blog if you find this useful.
Want to build professional website for your Business or Store, Get a free quote here
Click here to get Premium Plugins and Themes at rs.249. Get 20% Off on your first order “WELCOME20”