Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC not validate empty string

I have razor file where I define html form with text box for string:

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
        </fieldset>
     }

The problem is, that I want this field (model.name) not to be nullable, but razor validation allows string to be empty, when I add empty string to model it gives error. Any suggestions how to validate simply this string not to be empty anymore?

like image 771
Kote Avatar asked Jul 07 '13 10:07

Kote


People also ask

How to check string not empty c#?

To check if a given string is empty or not, we can use the string. IsNullorEmpty() method. The string. IsNullorEmpty() method accepts the string as an argument and returns true if a given string is null or an empty string ("") otherwise it returns false if a string is not empty.

How to check empty string in asp net?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String.


2 Answers

You probably need to set the DataAnnotation attribute

[Required(AllowEmptyStrings = false)]

on top of your property where you want to apply the validation.
Look at this question here
RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation

Similar problem, more or less here.
How to convert TextBoxes with null values to empty strings

Hopefully, you'll be able to solve your problem

like image 136
sohaiby Avatar answered Oct 14 '22 10:10

sohaiby


what does your viewmodel look like?

You can add a DataAnnotation attribute to your Name property in your viewmodel:

public class MyViewModel
{
    [Required(ErrorMessage="This field can not be empty.")]
    public string Name { get; set; }
}

Then, in your controller you can check whether or not the model being posted is valid.

public ActionResult MyAction(ViewModel model)
{
    if (ModelState.IsValid)
    {
        //ok
    }
    else
    {
        //not ok
    }
}
like image 32
Thousand Avatar answered Oct 14 '22 12:10

Thousand