GET A QUOTE
Md Asik QR Code

How to restrict link in html form using jQuery

restrict link in html form

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.

				
					<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restrict Links in HTML Form</title>
    <script type="rocketlazyloadscript" data-minify="1" src="https://mdasik.com/wp-content/cache/min/1/jquery-3.6.4.min.js?ver=1713284604" defer></script>
    <script type="rocketlazyloadscript">window.addEventListener('DOMContentLoaded', function() {
        $(document).ready(function() {
            $('#form_online_quote').submit(function(event) {
                var textareaValue = $('#description_job').val();

                // URL validation
                var urlPattern = /^(?!.*(?:youtube\.com|youtu\.be))(?:(?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9-]+\.[a-z]{2,}(?:\/\S*)?$/;
                if (urlPattern.test(textareaValue)) {
                    $('#textarea_error').css('display', 'block');
                    event.preventDefault();
                    return false;
                }

                // Special character validation
                var specialCharPattern = /[\'^£$%&*()}{@#~><>|=_+¬]/;
                if (specialCharPattern.test(textareaValue)) {
                    $('#textarea_error').css('display', 'block');
                    event.preventDefault();
                    return false;
                }

                // Hide the error message if validation passes
                $('#textarea_error').css('display', 'none');

                return true;
            });
        });
    });</script>
</head>
<body>

<form id="form_online_quote">
    <label for="description_job">Job Description:</label>
    <textarea id="description_job" name="description_job"></textarea>
    <div id="textarea_error" style="display: none; color: red;">Invalid input. Links are not allowed.</div>
    <button type="submit">Submit</button>
</form>

<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script></body>
</html>

				
			

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:

Restrict Links in HTML Form

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”

Related Posts

Write a comment

Recent Posts

Categories

Tags

SCAN ME TO GET CURRENT PAGE LINK
Md Asik QR Code
Thank you for submitting. We’ll get back to you shortly