Here I am trying to do both client and server side validation in Age property of model class contact for which i have used custom validation attribute i.e Digt and UpperCase attribute for checking uppercase and digit in input, if not should give error message as specified in validation attribute.
Now, the problem is that on click of submit button the validation message is displayed as required but before the click of submit button the error message is not displayed even though the condition for input is not meet.
Any Help will be great and highly appreciated.Thank you
Below is my both digit and uppercase custom validation attribute
Uppercase Attribute
public class UpperCaseAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string suppliedValue = (string)value;
var hasUpperChar = new Regex(@"[A-Z]+");
var match = hasUpperChar.IsMatch(suppliedValue);
if (match == false)
{
return new ValidationResult("Input Should Have Uppercase ");
}
}
return ValidationResult.Success;
}
}
Digit Attribute
public class DigitAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string suppliedValue = (string)value;
var hasNumber = new Regex(@"[0-9]+");
var match = hasNumber.IsMatch(suppliedValue);
if(match == false)
{
return new ValidationResult("Input Should Have Number");
}
}
return ValidationResult.Success;
}
}
Below is my metadata for contact model class
ContactMetadata
public class ContactMetadata
{
public int Id { get; set; }
[Required(ErrorMessage = "Age is Required")]
[UpperCase]
[Digit]
public string Age { get; set; }
}
Below is my view
Create View
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>