1

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, '');
}

2 Answers 2

1

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, '');
        }
Sign up to request clarification or add additional context in comments.

6 Comments

I don't have Model for this view, I have mentioned it in question.
Thanks! But if I copy html from somewhere else & paste it in text box, replace is not happening.
Can you post your html
If I type <h1> in notepad, copied it & pasted into search text box. After hitting search button, 500 error is there.
Got an Idea. just changed event from keypress to onblur.
|
0
<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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.