Simple Validation for a Single Text Box in ASP.NET MVC - asp.net-mvc

I have added a text box to a simple form in ASP.NET MVC and I want a client-side 'required' validation for this.
I know I can do this using a strongly typed model view but I would like to do it manually in this case. Is there a simple way to perform this?
I tried setting the Model/property name of the Html.ValidationMessage helper to the input name but this didnt work:
#Html.TextBox("emailStr" )
#Html.ValidationMessage("emailStr","* Required")

Assuming you use default jQuery validation plugin, you can use Rules.Add method on client side for this
$("#emailStr").rules("add", {
required: true,
messages: {
required: "* Required",
}
});
Also, do not forget to include jquery.validate.min.js

Not sure why you would want to do it manually - but I don't think you can use #Html.ValidationMessage unless you use a TextBoxFor. You can't use the TextBoxFor unless you have a model to work with inside the view.
You could write some javascript/jquery to find the textbox and make sure it's not empty, and if it is, unhide an element with the validation message in it.

Related

MVC c# prevent xss

I have a simple email form on my site with mvc c#.
If i added into the text box alert("test") I get the below exception:
A potentially dangerous Request.Form value was detected from the client (Message="<script>alert("test"...").
I dont want a user to be able to insert javascript. I need for html encode i would i do this on this field
#Html.TextAreaFor(model => model.Message, new { #style = "width:800px;height:300px;" })
Option 1: look at the accepted answer at:
HTML-encoding lost when attribute read from input field
Option 2: Put the [AllowHtml] attribute on the model item that binds to this textbox and that will let the value into your controller where you can use HtmlEncode.
Option 3: Put the [ValidateInput(false)] attribute on your controller action, this lets everything through no matter what and then you can do your own custom validation for everything
Use System.Web.HttpUtility.HtmlEncode to encode all user input and avoid XSS atacks.

How can I disable a textbox if there are modelstate errors in mvc?

I am doing some server stuff that could potentially fail (not likely) but something can go wrong. I want to stop the user from going any further so I want to disable the input so that they have to refresh the page. How can I disable it based on ModelState errors. If any errors exist, disable this box and I only want to do it when the page is initially loaded. My problem is not necessarily how to do it but more what is the standard and the best way to do it. I could have a ViewBag that holds a true false for disabling it but not sure if that's the best route, any suggestions?
Let's suppose that you have a POST controller action that does some processing and adds errors to the ModelState if it fails which pretty standard. Now inside the view you could:
#Html.TextBoxFor(
x => x.SomeProperty,
!ViewData.ModelState.IsValid ? new { #readonly = "readonly" } : null
)
or write a custom helper that will do the job and simplify things up for you:
#Html.MyTextBoxFor(x => x.SomeProperty)
Could be useful if you need this behavior for multiple input fields.
You can find out if the form is valid with jquery:
if($('form').valid()){
}

Getting client side validation to work with Telerik MVC Window

I am using a telerik mvc window extension that is triggered from a custom template link in a telerik mvc grid. The window is modal and it contains a form for editing data. After successfully implementing client side validation using a standard html page, I have been trying to implement it in the telerik mvc window. I have not been able to do so successfully. Is this possible? Does anybody have a working example of this?
Thanks
Ozzy
You need to load to page in an IFrame. To do this, make sure the url in LoadContentFrom method starts with http or https:
<%= Html.Telerik().Window()
.Name("Window")
.LoadContentFrom("http://www.example.com")
%>
if you're using the Url.Action() helper to get the url, include the protocol parameter to get the full url.
E.g
Url.Action("action name","controler name", "http") <--may also need to include route values or null route value dictionary.
To close to window, you'll need to make a call back to the parent view, try this:
add a bool isValid property to your model
if succesfully validated, reload the view with isValid equals true
onload:
var isValid = '<%: Model.IsValid%>';
if(isValid == 'True')
{
window.parent.$('#MyWindow').data('tWindow').close();
}
It is possible. First make sure you have your ViewModel property that needs validation decorated with the appropriate attribute. Eg: [Required(ErrorMessage = "this is required")]
Then include all the client validation scripts found in telerik's folder in your application.
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
Make sure you use the latest build of teleriks extensions. hth.

Required Attribute for bool value type when used as checkbox

I'm running into a problem where I have a simple add/edit form and using client-side validation (jQuery/MicrosoftMvcJQueryValidation.js) which is generated from data annotations and enabled client side by calling the following in my view:
<% Html.EnableClientValidation(); %>
This seems to work fine for most elements, however I have an instance where I have a boolean property which is rendered as a checkbox using:
<%= Html.EditorFor(model => model.Chargeable)%>
Which can be either true/false (ticked/unticked).
As the bool is a value type, and not nullable, it is being rendered as a required property and displays an error (client side) when the form is submitted reading "The Chargeable field is required.", however, as the HTML that is generated is two part (both checkbox and hidden value) it will pass the post back validation.
After browsing the MVC 2 source code, I've managed to put a "quick and dirty" fix in for the moment, which is to set:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Any one else got any ideas or suggestions on how I can get around this?
IMO, I dont think MVC should be setting the client-side required validator for checkboxes rendered using the Html.EditorFor/Html.CheckBox(For) methods.
Note: I'm using the ASP.NET MVC 2 RC2 and the MicrosoftMvcJQueryValidation.js from the matching MVC Futures release.
I suppose the easiest way of handling it is to call the rules("remove", [rules]) function on the elements (mainly checkboxes) that I want to remove the client-side validation from:
<script type="text/javascript">
$(document).ready(function() {
$('#Chargeable').rules('remove', 'required');
});
</script>

How to Access the CheckBox Value in ASP.NET MVC without using method parameter

I use the following HTML helper to generate check box:
<%= Html.CheckBox("DeluxeFeature")%>
Now I want to access the value of this checkbox in my controller. How should I do this? I am not going to use the method parameter name, for the reason that there are a lot of checkboxes and putting all of them in the parameter will clutter the method.
I try to use
Request.Form["DeluxeFeature"]
But the behavior is very weird; if the checkbox is not ticked, then the Request.Form["DeluxeFeature"] returns "false", which is expected. But if the checkbox is ticked, then it retruns "true, false".
Very weird, isn't it?
This thread on the asp.net forums explains the behavior - there's even a comment by Phil Haack from the ASP.NET MVC project team (bonus!!).
So the best way to handle it if you're not using the helpers/model binders as posted by levib seems to be
Request.Form.GetValues("DeluxeFeature")[0]
This worked for me.
var checkbox = Request.Form.Get("DeluxeFeature");
if (checkbox.Contains("true"))
{
//Whatever code if the checkbox is checked.
}

Resources