MVC not validate empty string

后端 未结 3 2005
傲寒
傲寒 2021-01-11 18:46

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

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        

        
相关标签:
3条回答
  • 2021-01-11 19:21

    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")]
    
    0 讨论(0)
  • 2021-01-11 19:28

    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
        }
    }
    
    0 讨论(0)
  • 2021-01-11 19:32

    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

    0 讨论(0)
提交回复
热议问题