Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation of empty strings

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

like image 942
Don Box Avatar asked Aug 31 '25 22:08

Don Box


2 Answers

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

like image 170
Jeremy Thompson Avatar answered Sep 03 '25 14:09

Jeremy Thompson


You could always use a regular expression.

For example:

[RegularExpression(@".*\S+.*$", ErrorMessage = "Field Cannot be Blank Or Whitespace"))]
public string FirstName { get; set; }
like image 39
SBFrancies Avatar answered Sep 03 '25 14:09

SBFrancies