March 18, 2013

jQuery remove email in textarea

Question by JR Galia

I have HTML textarea.

<textarea> ... </textarea>

I don’t want users to enter any email address in the textarea. What is the best approach on this using jQuery? How to remove email entered before submitting the form?

I only need hint and references. Thanks.

Answer by nbrooks

jsFiddle Demo

Use a regular expression to match the email addresses, and then replace them with blank strings.

$(function() {
    $("textarea").change(function() {
        $(this).val( function(idx, val) {
            return val.replace(/b(w)+@(w)+.(w)+b/g, "");

Answer by Starx

Although a genuine concern, the use of JavaScript here will not give you the result you are expecting. The problem is that you want to remove the email addresses automatically before you are submitting the form. This is not a user friendly approach.

You have to alert the user that he cannot enter a email address in the box and ask him to correct the mistake.

Removing the email address part is MUCH SAFER DONE IN SERVER Level. Like from PHP, ASP, JSP etc.

Alert the user of email address like this.

$("textarea").change(function() {
    if(/^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/.test($(this).val()) {
         alert('you have entered email address, which is not allowed');

Then remove the email for your Server Application.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!