Ensuring Form Validation in ASP.NET Core Using the Form Tag and OnSubmit Function to Intercept Form Submission

In my ASP.NET Core 2.0 project, I am utilizing the form tag for submission purposes. I am now looking to incorporate client-side validation for my form submission. To achieve this, I have included the onsubmit attribute in my form tag as shown below:

<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">

Additionally, I have created a function like this:

function validationFunction(e) {
    //CheckStuff
    e.preventDefault();
}

However, despite triggering the function properly, neither e.preventDefault() nor return false seem to prevent the submission process.

How can I successfully prevent my form submission from going through?

PS. I am aware that I could handle this scenario by managing the button click and submitting the form only after validation is complete. Nonetheless, I am curious as to why the above approach does not work in ASP.NET Core or if there is something I am overlooking.

Answer №1

In order to prevent the form from submitting, the onsubmit attribute should be used and return false should be included.

<form id="formId" asp-action="ActionName" onsubmit="return validationFunction(Event)">

Answer №2

To ensure accuracy and simplicity, it is recommended to define validation within the class. Here is an example:

public class Movie
{
public int ID { get; set; }

[StringLength(60, MinimumLength = 3)]
[Required]
public string Title { get; set; }

[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
[Required]
public string Rating { get; set; }
}

For more information, visit Microsoft's validation tutorial

You can also use JavaScript and HTML for validation purposes.

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

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Checking if a string is present in an array object with Angular.js using a filter function

In my Angular and Firebase app, users can create new discussion topics and vote on existing ones. When a user is logged in, their username is stored in currentUser.username. If they've upvoted a topic, their username will also be added to the array of ...

How can you utilize a bind function to deactivate a button?

Can someone help me figure out how to temporarily disable a button using the bind function for 10 seconds? jQuery('#wsf-1-field-155').bind('click', function() { ScanRegistration(); setTimeout(function() { jQuery('#wsf- ...

The issue with the Ajax infinite scrolling gallery is that it repeatedly displays the same images multiple times

I'm currently working on developing a straightforward gallery page that dynamically adds elements as you scroll to the bottom. To achieve this, I am using Django to render an HTML snippet from the backend and then utilizing JavaScript to append it to ...

I'm looking to input data into a PHP table using JavaScript. Is there a way to accomplish this using a database rather than relying on localStorage?

I am looking to transition from using localStorage to working with a database in the code below. I understand that JavaScript is a client-side language and PHP is server-side. Instead of storing data in localStorage, I would like to retrieve and store data ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

Can Ajax and jQuery be utilized on a webpage in conjunction with a cron job?

These are the steps my page performs: Retrieve an array from a different server (first.php) Parse values using a PHP script Send parsed values using an AJAX call In the next page (second.php) that is called by AJAX, perform MySQL queries If values meet c ...

Upload files either one at a time or in bulk

Encountering an issue with file upload functionality. When uploading multiple files at once, there are no problems. However, when uploading single files one at a time, each new upload overrides the previous one. Looking for a solution to this problem. Be ...

Tips for displaying Vue Components on an HTML5 canvas surface

How can I incorporate an htmlcanvas as the webpage background and overlay Vuejs components on top of it? I know the answer must exist, but I'm not sure where to start looking. ...

Adjusting the opacity of the background image in the section - focus solely on the background

This section is what I'm working on. <section ID="Cover"> <div id="searchEngine">hello</div> </section> I am trying to achieve a fade in/out effect specifically for the background image of the Cover section. T ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

Unresponsive Three.js OrbitControls

*Update: I'm feeling a bit confused because I don't believe my function is causing this issue. It seems that simply double-clicking without moving the mouse triggers this behavior consistently, even in the Three.js example. I'm still unsure ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

The issue with mocking collections using JSON files in Backbone is that it is not properly triggering the success callbacks in

For my project, I am exploring the use of .json files to mock GET requests in a backbone collection. Here is an example of my sample file: [ { "id": '11111', "name": "Abdominal Discomfort", "favori ...

Implementing Canvas Offset in a jQuery Mobile Environment

I have positioned a pen ready for use at this location. http://codepen.io/prantikv/pen/LEbRKY Currently, I am utilizing a canvas to track mouse movements or touch input. It performs as expected when jQuery or jQuery mobile is not included. However, upon ...

Utilizing setColumns() function within Google Charts for JSON data tables

Is there a feature in the Google Charts API that functions similar to setColumns() for working with JSON data? I'm aiming to reduce PHP calls by consolidating my data into a single array and then specifying which columns Google Charts should utilize. ...

Modify URL parameters in Vue.js based on specific conditions to remove key-value pairs

Currently, I am working on a filter feature where I need to append query parameters to the URL based on user selections. If a user chooses a specific option, I want to modify the query string accordingly. Here's an example of my current URL structure: ...

Replace specific text with a span element around it?

I am working with the following HTML code: <p class="get">This is some content.</p>. My goal is to modify it so that it looks like this: <p class="get">This is <span>some</span> content.</p>. To achieve this, I have ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...