Invalid input: The provided string is not recognized as a valid number

Currently, I am developing a website with Angular that is linked to an ASP.Net backend for database access. The error I am encountering pertains to a custom Async Validator integrated into a Form Control. This validator serves the purpose of verifying if an input ID exists in the database before allowing form submission.

An unusual aspect is that the error is not consistently occurring during input validation; it mostly functions correctly. However, the only scenario where the error appears is when the input string begins with "0" and contains either "8" or "9" at specific positions. If the string commences with any other digit, no HTTP 400 error is thrown.

For instance, when the input is "01823", the error message reads

"{"":["Input string '01823' is not a valid number. Path '', line 1, position 5."]}"
, accompanied by
"Http failure response for https://localhost:5001/api/FS/vendor: 400 Bad Request"
. The position specified in the error message always corresponds to the last character in the string.

Despite meeting the specified criteria in the database, the error persists regardless of the existence of the input value.

Validation Procedure

// Validate Vendor ID
invalidVendor(): AsyncValidatorFn {
  return (control: AbstractControl): | Observable<{ [key: string]: any } | null> | Promise<{ [key: string]: any } | null> => {
    if (control.value === null || control.value === '') {
      return of(null);
    }
    else {
      return control.valueChanges.pipe(
        debounceTime(500),
        take(1),
        switchMap(_ =>
          this.dbService.checkVendor(control.value).pipe(map(v =>
            v == '' ? { invalidVendor: { value: control.value } } : null)
          )
        )
      );
    }
  };
}

dbService.checkVendor

// Check for valid vendor ID
public checkVendor(vendor: string) {
  var httpOptions = {
    headers: { 'Content-Type': 'application/json' },
    responseType: 'text' as 'json'
  };
  return this.http.post<string>('api/FS/vendor', vendor, httpOptions);
}

FsController.ValidVendor

// POST: api/FS/vendor
[HttpPost("vendor")]
public async Task<ActionResult<string>> ValidVendor([FromBody] string vendor)
{
  var result = await _fsContext.FS_Vendor.Where(x => x.VendorID.Equals(vendor)).FirstOrDefaultAsync();
  return result != null ? result.VendorID : "";
}

UPDATE:

The problem has been resolved by utilizing an object instead of a string. Nonetheless, the root cause behind this particular issue remains unknown, so I will continue investigating.

Answer №1

The 400 error is caused by the JSON parser mistaking a number starting with 0 as an Octal number, leading to an invalid Octal once it reaches 8.

Upon resolving the issue and investigating the cause of the error, I found this informative post that explained the situation within the parser:

https://example.com/understanding-json-errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

What are the additional HTTP request methods in addition to POST, PUT, DELETE, and GET that

I'm currently developing a web service with ASP.NET's WebAPI. From what I understand, the method name in the ApiController corresponds to the Uri. For example, PutProducts for adding products. However, I am unsure about how to handle a method ...

What steps are involved in configuring uploadify to allow for drag and drop functionality when uploading images?

Is there a way to enable users to upload multiple images through drag and drop? Currently, I am using the Uploadify plugin to upload multiple images and display them in a datalist, which is working great. However, I would like to enhance the user experien ...

Leverage the generic parameter type inferred from one function to dynamically type other functions

I am in the process of developing an API for displaying a schema graph. Here is a simplified version of what it entails: interface Node { name: string; } type NodeNames<T extends Node[]> = T[number]["name"]; // Union of all node names as strings ...

Execute a painting operation on several controls simultaneously

I am facing a minor issue. How can I overlay this specific image on top of any controls such as textbox? Here is the snippet of my code: Private Sub GroupBox6_Paint(sender As Object, e As PaintEventArgs) Handles GroupBox6.Paint If txtStatus.Text = "C ...

Angular2 Final: Issue with inline template - incorrect format for number pipes

Problem <h2>{{totalTargetValue | currency:'EUR':true:'2'}}</h2> Issue Error while using inline template: the specified digit info for number pipes is invalid. Do you have any suggestions on how to resolve this error? ...

Incorporate a Python algorithm into a C# command-line application

As a student working on developing a telegram bot in C#, I have encountered challenges integrating a communication model written in Python into the bot's code. The ideal solution seems to be using Python.NET, as my model relies on pandas, sklearn, and ...

What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types For example: type Foo = string | number I need to receive this type and convert it into an array of the individual types within the union type TransformedFoo = ToUnionOfArray<Foo> // => string[] ...

There is a potential for the object to be 'undefined' when calling the getItem method on the window's local storage

if (window?.sessionStorage?.getItem('accessToken')?.length > 0) { this.navigateToApplication(); } Encountering the following error: Object is possibly 'undefined'.ts(2532) Any suggestions on how to resolve this issue? I am attem ...

Is there a way to retrieve the return value from the Telerik RadGrid GridView1_ItemInserted event?

I am working with a telerik radgrid that is performing an insert operation using an objectdatasource. The insert method being called by the objectdatasource has a boolean return value that I need to verify in the radgrid's ItemInserted event. Does an ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Enhanced by JQuery: Selecting items in a CheckBoxList

Is there a way to use jQuery on the client side to check a specific item in a CheckBoxList within a user control? <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AppCon %>" SelectCommand ...

Building SVG components in React with TypeScript and styling them using SCSS

I've been experimenting with using Webpack to import SVG files as components in React Typescript. However, I'm running into trouble when it comes to styling the SVGs with SCSS. I've tried targeting a custom attribute in my CSS selector, but ...

Creating a type definition for a TypeScript InfiniteScroll component in React

I am currently in the process of developing an InfiniteScroll component to be used like this: import { getData } from 'api'; import { InfiniteScroll } from 'components'; export const App = () => ( <InfiniteScroll fetcher={page ...

Challenges encountered when using the SerialPort class in .NET

I am currently investigating the reason why certain USB serial port adapters are not fully compatible with .NET. The issue arises after utilizing the SerialPort.Write() function. When any of the SerialPort.Readxxx() methods are called, they seem to block u ...

Authenticate users by accessing their login information stored in a MongoDB database using Node.js and Express

I have been experimenting with various techniques, and incorporating Passport middleware has brought me the closest to achieving this task. I suspect there might be a final step missing for everything to function correctly, as I am not encountering any err ...

Display TreeView in DataGridView Cells in Windows Forms

I am looking to add a TreeView column to my DataGridView. I have tried to implement the example provided in this resource by extending the TreeView as shown below. public class TreeViewEditingControl : TreeView, IDataGridViewEditingControl public class T ...

A guide on transferring files to a PHP server using HttpClient and FormData within an Ionic framework, along with instructions on receiving files in PHP

I have an input file in mypage.html on Ionic and I want to send this file to PHP for uploading it onto the server. In mypage.page.html, I have created an input field for the file name and another input field for the file to be uploaded. <ion-header> ...

What is the procedure for updating a property within an intersection type in Typescript?

Consider the following types: type BaseAnimal = { species: string owner: boolean } type Cat = BaseAnimal & { species: 'cat' hasTail: boolean } type Dog = BaseAnimal & { species: 'dog' likesWalks: boolean } type An ...

The specialized middleware in Next.js gets dispatched to the browser

Attempting to retrieve user information based on the current session, I created a small _middleware.ts file. In order to get the users' data, I imported a prisma (ORM) client. However, upon loading the page in the browser, an error message appeared: ...