4

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

7
  • you know, you can use [StringLength] and.. what deters you from using @Html.TextBoxFor()? Commented Jul 27, 2018 at 7:08
  • msdn.microsoft.com/en-us/library/… try this? Commented Jul 27, 2018 at 7:09
  • @BagusTesa I am already using StringLength. How is Html.TextBoxFor better than <input asp-for="FirstName" ? Commented Jul 27, 2018 at 7: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 Commented Jul 27, 2018 at 7:34
  • [Required(AllowEmptyStrings = false)] - is this work? Sounds like you can write custom RequiredAttribute with IsNullOrWhiteSpace check. Commented Jul 27, 2018 at 7:34

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This is server side validation, correct? The form needs to be posted in order for the validation to kick in
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...
2

You could always use a regular expression.

For example:

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

15 Comments

Nice. Albeit regular expressions are nasty.
as in, it works on C# side but sometimes wont on js side... look behind.
@BagusTesa "sometims wont" ? What does that even mean?
@SBFrancies I will mark your comment as answer, however I was looking for something better than RegExp. This can be avoided using ViewState.IsValid or having a custom client validation
Thanks - I agree, not a fan of regular expressions personally.
|
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")]

Comments

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);
    }

}`

Comments

-1

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 .

1 Comment

String Length or MinLength doesn't prevent whitespace.being valid

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.