Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am doing a web application using asp.net core the problem is that I receive this error every time I launch the application I want to know what does that error mean

This Are Error Header:
An unhandled exception occurred while processing the request.
FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, string format, ParamArray args)


This Are Error Details:
FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.FormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.Format(IFormatProvider provider, string format, object arg0, object arg1)
System.ComponentModel.DataAnnotations.RegularExpressionAttribute.FormatErrorMessage(string name)
Microsoft.AspNetCore.Mvc.DataAnnotations.ValidationAttributeAdapter<TAttribute>.GetErrorMessage(ModelMetadata modelMetadata, object[] arguments)
Microsoft.AspNetCore.Mvc.DataAnnotations.Internal.RegularExpressionAttributeAdapter.GetErrorMessage(ModelValidationContextBase validationContext)
Microsoft.AspNetCore.Mvc.DataAnnotations.Internal.RegularExpressionAttributeAdapter.AddValidation(ClientModelValidationContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultValidationHtmlAttributeProvider.AddValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.ValidationHtmlAttributeProvider.AddAndTrackValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, string expression, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.AddValidationAttributes(ViewContext viewContext, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateInput(ViewContext viewContext, InputType inputType, ModelExplorer modelExplorer, string expression, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateTextBox(ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.GenerateTextBox(ModelExplorer modelExplorer, string inputTypeHint, string inputType, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Contacts_Create.<ExecuteAsync>b__20_0() in Create.cshtml
+
            <input asp-for="PhoneNumber" type="tel" class="form-control">
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Contacts_Create.ExecuteAsync() in Create.cshtml
<big>+
    ViewBag.Title = "Register";</big>
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync<TFilter, TFilterAsync>()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)


This are the class that i defined validation
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Contact.Models
{
    public class Contacts
    {
        public int ContactId { get; set; }
        [Required (ErrorMessage ="Please Provide A Value For First Name")]
        public string FirstName { get; set; }
        [Required (ErrorMessage ="Please Provide A Value For The Last Name")]
        public string LastName { get; set; }
        [Required(ErrorMessage ="Please Provide A Value For The WorkPlace ")]
        public string WorkPalce { get; set; }
        [Required(ErrorMessage ="Please Provide A Value For Phone Number")]
        [RegularExpression(@"^(01)[0-9]{9,}$", ErrorMessage = "The Phone Number Does 
        Not Match The Pattern @(201)[0-9]{9}")]
        public int PhoneNumber { get; set; }
        [Required(ErrorMessage ="Please Provide Email Adress")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z] 
        {2,5})$", ErrorMessage ="Invalied Email Pattern")]
        public string Email { get; set; }
        [Required(ErrorMessage ="Please Provide A Data Of Birth")]
        [RegularExpression(@"^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$", ErrorMessage ="Please 
        Enter A valid Date Of Birth Matches Pattern DD/MM/YYYY")]
        public string DateOfBirth { get; set; }
        public string Note { get; set; }
        
    }
}


This are the HTML CODE
HTML
 @model Contacts

@{ 
    ViewBag.Title = "Register";
}

<div class="container-fluid">
    <form asp-action="Create" asp-controller="Contacts" method="post">
        <div class="form-group">
            <label asp-for="FirstName">First Name</label>
            <input type="text" class="form-control" asp-for="FirstName">
            <span asp-validation-for="FirstName"></span>
        </div>
        <div class="form-group">
            <label asp-for="LastName">Last Name</label>
            <input type="text" class="form-control" asp-for="LastName">
            <span asp-validation-for="LastName"></span>
        </div>
        <div class="form-group">
            <label asp-for="WorkPalce">Work</label>
            <input type="text" class="form-control" asp-for="WorkPalce">
            <span asp-validation-for="WorkPalce"></span>
        </div>
        <div class="form-group">
            <label asp-for="PhoneNumber">Phone Number</label>
            <input asp-for="PhoneNumber" type="tel" class="form-control">
            <span asp-validation-for="PhoneNumber"></span>
        </div>
        <div class="form-group">
            <label asp-for="Email">Email</label>
            <input type="email" class="form-control" asp-for="Email">
             <span asp-validation-for="Email"></span>
        </div>
        <div class="form-group">
            <label asp-for="DateOfBirth">Date Of Birth</label>
            <input type="date" class="form-control" asp-for="DateOfBirth">
            <span asp-validation-for="DateOfBirth"></span>
        </div>
        <div class="form-group">
            <label asp-for="Note">Comments</label>
            <textarea class="form-control" asp-for="Note"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
        
    </form>
</div>


Need to know what is the problem

What I have tried:

tried to remove the input for the phone number that makes the problem the app works and tried to change the regular expression for that input doesn't work
Posted
Updated 15-Jan-20 4:12am

The error is caused by the ErrorMessage on the RegularExpression attribute for the PhoneNumber property:
C#
[RegularExpression(@"^(01)[0-9]{9,}$", ErrorMessage = "The Phone Number Does Not Match The Pattern @(201)[0-9]{9}")]
The error message will be passed to String.Format, passing in the property name as the single format parameter.

Your error message contains the format placeholder {9}, which would be replaced with the 10th format parameter passed in.

Since there weren't 10 format parameters passed in, you get the exception from your question.

You need to escape the braces within the error message by doubling them:
C#
[RegularExpression(@"^(01)[0-9]{9,}$", ErrorMessage = "The Phone Number Does Not Match The Pattern @(201)[0-9]{{9}}")]
Alternatively, provide a more meaningful error message - most users won't know what a regular expression is, let alone how to construct a string to match one.
 
Share this answer
 
Phone numbers are one of the hardest things to run validators for; as there are many different formats, lengths, and separators involved- and that doesn't even touch business numbers with extensions.

What I do is break up the phone number into its individual components; displaying 3 input fields (type=number) from US phone numbers, and then I combine them in code into the format I choose.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900