Reputation: 85
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>
Upvotes: 3
Views: 6129
Reputation: 372
Your validation attributes have to implement IClientModelValidator and you have to write your own validation logic on client-side as well:
public class UpperCaseAttribute: System.ComponentModel.DataAnnotations.ValidationAttribute, IClientModelValidator
{
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;
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
AttributeUtils.MergeAttribute(context.Attributes, "data-val", "true");
AttributeUtils.MergeAttribute(context.Attributes, "data-val-uppercase", FormatErrorMessage(context.ModelMetadata.GetDisplayName()));
}
}
public class AttributeUtils
{
public static bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
You have to include jquery.validate.min.js and jquery.validate.unobtrusive.min.js in html. Then add the corresponding rules and functions after the content is loaded as follows:
$.validator.addMethod("uppercase",
function (value, element, params) {
return value === value.toUpperCase();
});
$.validator.unobtrusive.adapters.add("uppercase",
params,
function (options) {
options.rules[index] = options.params;
options.messages[index] = options.message;
});
Upvotes: 4
Reputation: 2414
When you create a custom validation attribute for server side, you need to write your own custom validation script for client side as well. In asp.net mvc, the client side validation was to be hooked with the unobtrusive validation scripts. For .NET Core, you can refer this Defining client validation rules on the client side
Upvotes: 1