10

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Kote
  • 683
  • 1
  • 9
  • 27

3 Answers3

22

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

sohaiby
  • 1,168
  • 3
  • 24
  • 39
5

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
    }
}
vidriduch
  • 4,753
  • 8
  • 41
  • 63
Thousand
  • 6,562
  • 3
  • 38
  • 46
0

This is what worked for me:
Use the following line to not accept empty string

[Required (AllowEmptyStrings = false)]

and this one to not allow white space

[RegularExpression (@".*\S+.*", ErrorMessage = "No white space allowed")]
Tim
  • 5,435
  • 7
  • 42
  • 62
Flowra
  • 1,350
  • 2
  • 16
  • 19