3

How can I make the form first name input field not accept empty strings with space characters " "

    <form asp-action="SaveRegistration" autocomplete="off">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="FirstName" class="control-label"></label>
            <input asp-for="FirstName" class="form-control" />
            <span asp-validation-for="FirstName" class="text-danger"></span>
        </div>

Model:

public class ContactInfo
{
    [Required(ErrorMessage = "This field is required")]
    [StringLength(50)]
    [DisplayName("First name")]
    public string FirstName { get; set; }
}

With [Required] attribute the user can still submit with a string with just space characters " "

I know it's a simple question, but I am novice in ASP.NET MVC

Don Box
  • 3,166
  • 3
  • 26
  • 55
  • you know, you can use [`[StringLength]`](https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute.aspx) and.. what deters you from using `@Html.TextBoxFor()`? – Bagus Tesa Jul 27 '18 at 07:08
  • https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.minlengthattribute(v=vs.110).aspx try this? – Bola Jul 27 '18 at 07:09
  • @BagusTesa I am already using StringLength. How is `Html.TextBoxFor` better than ` – Don Box Jul 27 '18 at 07:30
  • @Bola How does `MinLength` helps? I want to prevent user from entering string of just space characters, I don't want to restrict to a minimum length – Don Box Jul 27 '18 at 07:34
  • `[Required(AllowEmptyStrings = false)]` - is this work? Sounds like you can write custom `RequiredAttribute` with `IsNullOrWhiteSpace` check. – Tetsuya Yamamoto Jul 27 '18 at 07:34
  • @TetsuyaYamamoto The value of AllowEmpyStrings is false by default – Don Box Jul 27 '18 at 07:35
  • @TetsuyaYamamoto the issue I think is in the validation in the generated JS client side code. It doesn't check for space characters strings – Don Box Jul 27 '18 at 07:36

5 Answers5

7

Usage:

[NotNullOrWhiteSpaceValidator]
public string FirstName { get; set; }

How to make your own Attributes:

using System;
using System.ComponentModel.DataAnnotations;

public class NotNullOrWhiteSpaceValidatorAttribute : ValidationAttribute
{
    public NotNullOrWhiteSpaceValidatorAttribute() : base("Invalid Field") { }
    public NotNullOrWhiteSpaceValidatorAttribute(string Message) : base(Message) { }

    public override bool IsValid(object value)
    {
        if (value == null) return false;

        if (string.IsNullOrWhiteSpace(value.ToString())) return false;

        return true;        
    }

    protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
    {
        if (IsValid(value)) return ValidationResult.Success;
        return new ValidationResult("Value cannot be empty or white space.");
    }
}

Here is implementation code for a bunch more validators: digits, email, etc: https://github.com/srkirkland/DataAnnotationsExtensions/tree/master/DataAnnotationsExtensions

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • Thanks! This is server side validation, correct? The form needs to be posted in order for the validation to kick in – Don Box Aug 16 '18 at 06:52
  • 1
    Correct, many people add client-side JavaScript validation, you should always have server-side validation as shown encase JavaScript is disabled on the clients' browser, eg Chrome or even Nintendo Wii. Typically Validation methods will be called via `if (Model.IsValid)` in the Controller. It's also possible to call these validations earlier in the pipeline... – Jeremy Thompson Aug 16 '18 at 09:17
2

You could always use a regular expression.

For example:

[RegularExpression(@".*\S+.*$", ErrorMessage = "Field Cannot be Blank Or Whitespace"))]
public string FirstName { get; set; }
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
2

The default behaviour is to reject empty strings. You can change this behaviour by setting AllowEmptyStrings to true docs

[Required(ErrorMessage = "This field is required")]
shakram02
  • 10,812
  • 4
  • 22
  • 21
1

Note:This is for .net MVC 4+

There is a Implementation of AllowEmptyStrings within [Required(ErrorMessage = " is required.")].

And this method returns true if an empty string is allowed; otherwise, false. The default value for this method is set to false. So no need to worry ! Test and verify the same.It should not allow single or multiple empty string.If not explicitly make it false and see if its work.

FYR` {

public class RequiredAttribute : ValidationAttribute
    {
        //
        // Summary:
        //     Initializes a new instance of the 
           System.ComponentModel.DataAnnotations.RequiredAttribute
        //     class.
        public RequiredAttribute();

        //
        // Summary:
        //     Gets or sets a value that indicates whether an empty string is 
       // allowed.
        //
        // Returns:
        //     true if an empty string is allowed; otherwise, false. The default 
        // value is false.
        public bool AllowEmptyStrings { get; set; }

        //
        // Summary:
        //     Checks that the value of the required data field is not empty.
        //
        // Parameters:
        //   value:
        //     The data field value to validate.
        //
        // Returns:
        //     true if validation is successful; otherwise, false.
        //
        // Exceptions:
        //   T:System.ComponentModel.DataAnnotations.ValidationException:
        //     The data field value was null.
        public override bool IsValid(object value);
    }

}`

Abdul Hadee
  • 113
  • 6
0

First

You can try stringlength or minlength data annotation

Second

you can use parsley.js

Its an amazing library for client side form validation .

I will recommend you to use both client side and server side validation .

Saurabh
  • 1,505
  • 6
  • 20
  • 37