1

I have this:

@Html.TextBoxFor(cModel => cModel.Value, new { id = "txtbLimit", @type = "int" })

And I want to make sure that what the user puts in there is an integer.

How can I do that?

EDIT: I dont parse this textBox with a value of a Model, so model validation is not what I want

EDIT2:

Model:

public class StorageConfigurationModel
{
    [Required]
    public int QueueMonitorConfigurationsID { get; set; }
    [Required]
    public PathType QueueMonitorConfigTypeName { get; set; }
    [Required]
    public string Location { get; set; }
    [Required]
    public UnitType QueueMonitorValueTypeName { get; set; }
    [Required]
    public ThresholdType Threshold { get; set; }
    [Required]
    [RegularExpression(@"\d*")]
    public int Value { get; set; }
}

public enum PathType
{
    Path
}
public enum UnitType
{
    MB, GB, TB, Files, Percentage
}
public enum ThresholdType
{
    Upper, Lower
}

Parse function:

    private static StorageConfigurationModel BindToModel(int id, string pathType, string threshold, string valueType, string location, int limit)
    {
        return new StorageConfigurationModel
        {
            QueueMonitorConfigurationsID = id,
            QueueMonitorConfigTypeName = (PathType)Enum.Parse(typeof(PathType), pathType),
            Location = Convert.ToString(location.Trim()),
            Value = Convert.ToInt32(limit),
            QueueMonitorValueTypeName = (UnitType)Enum.Parse(typeof(UnitType), valueType),
            Threshold = (ThresholdType)Enum.Parse(typeof(ThresholdType), threshold)
        };
    }

So when I put all the data in my view and click add, nothing is triggered.

With this I call the function that calls the modelbinder:

        $.post('@Url.Action("AddUpdateConfigs")',
            {id: @Model.QueueMonitorConfigurationsID , pathType: $('#ddlConfigTypeName').val(), threshold:$('#ddlThreshold').val(), valueType:$('#ddlValueTypeName').val(), location: $('#txtbLocation').val(), limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() },
            function(data){
                if (!data.Success){
                    alert(data.Description);
                }
                else{
                    //$('#gridView').load('/Storage/gvConfigurations');
                    $.get('@Url.Action("gvConfigurations", "Storage")',null,function(data){$('#gridView').html(data);},'html');
                }
            },'json');
5
  • 2
    It think MVC handle that automatically if Value is of type int. Commented Jun 11, 2013 at 12:34
  • Do you want to do this check client-side or server-side? Commented Jun 11, 2013 at 12:37
  • A good start : msdn.microsoft.com/en-us/library/ee256141(VS.98).aspx Commented Jun 11, 2013 at 12:37
  • I prefer a client side solution Commented Jun 11, 2013 at 12:40
  • checkout Knockout and Knockout-Validation if you are able to implement this at this stage of project. Make it easy to do ;-) Commented Jun 11, 2013 at 15:07

2 Answers 2

4

On your model, add this attribute to the top of Value:

[RegularExpression(@"(\d+)")]

and MVC will set it invalid server-side before it gets back to the controller in the POST -you can then easily handle it properly.

Now, if you're set on using it in JavaScript, then use this method:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

and then you can run that in the onkeydown event like this:

onkeydown="return isNumber(this.value);"

EDIT

To get an error message in there you should be able to do something like this:

[RegularExpression(@"(\d+)", ErrorMessage="Please enter numeric values only.")]
Sign up to request clarification or add additional context in comments.

13 Comments

I'm not parsing the data that the user puts into a Model so this is not valid for me.
@AnnArbor87, have a look at my edit. And what are you doing with the data? If you're not POSTing the data back into the model, what are you doing?
The Regular expresion gives me an error saying:"Unrecognized escape sequence". I was posting the data and making a query. Now I changed and I'm parsing it to use this mvc features. So what is better? validation with the model or JS?
@AnnArbor87, validation with the model is better because it can't get past the server-side validation, and please see my edit for the issue you saw with the RegularExpression. Client-side validation is a nicety that makes the application look prettier and prevents the post back.
@AnnArbor87 put a @Html.ValidationMessageFor(cModel => cModel.Value) and try to read up on stuff so you understand what you are doing. :-)
|
-1

I think you can use a ViewModel class that match with your user interface elements, instead of use directly your Model class to pass the info to the post action.

For instance:

public class StorageConfigurationViewModel
{
[Required()]
public int pathType {get;set;}
[Required()]
public int threshold {get;set;}
[Required()]
public int valueType {get;set;}
[Required()]
public int location {get;set;}
[Required()]
public int limit {get;set;}
[Required()]
public int config {get;set;}
}

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.