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
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
You could always use a regular expression.
For example:
[RegularExpression(@".*\S+.*$", ErrorMessage = "Field Cannot be Blank Or Whitespace"))]
public string FirstName { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With