AK47
AK47

Reputation: 3797

Best way to prevent HTML Code in Textbox MVC Razor View

I have following code on my view. This HTML code is used for search in website. This view is not strongly typed view, so I can apply use DataAnnotation through model. What is best view to validate that, this textbox should accept only alpha numeric characters?

HTML

<form action="Search" method="post" >
        <div class="col-md-8">
            <input type="text" name="name" placeholder="search" class="fullwidth" onkeypress="return BlockingHtml(this,event);" />
        </div>
        <div class="col-md-4">
            <input type="submit" title="Search" value="Search" />
        </div>
    </form>

Javascript

function BlockingHtml(txt) {
    txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}

Upvotes: 1

Views: 1760

Answers (2)

AK47
AK47

Reputation: 3797

<form action="Search" method="post" >
        <div class="col-md-8">
            <input type="text" name="name" placeholder="search" class="fullwidth" onblur="return BlockingHtml(this,event);" />
        </div>
        <div class="col-md-4">
            <input type="submit" title="Search" value="Search" />
        </div>
    </form>

Changed event onkeypress to onblur.

Upvotes: 0

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

Model:-

[StringLength(100)]
[Display(Description = "Name")]
[RegularExpression("(/[^a-zA-Z 0-9\n\r.]+/g", ErrorMessage = "Enter only alphabets and numbers of Name")]
public string Name{ get; set; }

Updated:-

View:-

 <form action="Search" method="post" >
            <div class="col-md-8">
                <input type="text" name="name" id="txt" placeholder="search" class="fullwidth" onkeypress="BlockingHtml(this);" />
            </div>
            <div class="col-md-4">
                <input type="submit" title="Search" value="Search" />
            </div>
        </form>


function BlockingHtml(txt) {
            txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
        }

Upvotes: 1

Related Questions