I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit
tag on my form like this:
<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">
and I have a function like this:
function validationFunction(e) {
//CheckStuff
e.preventDefault();
}
Now when I submit my form, the function is triggered properly but the e.preventDefault()
doesn't stop the submission. Nor does return false
.
How can I prevent my submission from pleting?
PS. I know that I could probably handle the case with the button click and submit my form when I plete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?
I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit
tag on my form like this:
<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">
and I have a function like this:
function validationFunction(e) {
//CheckStuff
e.preventDefault();
}
Now when I submit my form, the function is triggered properly but the e.preventDefault()
doesn't stop the submission. Nor does return false
.
How can I prevent my submission from pleting?
PS. I know that I could probably handle the case with the button click and submit my form when I plete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?
Share Improve this question edited Apr 11, 2018 at 16:08 Anastasios Selmani asked Dec 7, 2017 at 15:46 Anastasios SelmaniAnastasios Selmani 3,6893 gold badges35 silver badges49 bronze badges 2-
asp-action
defines the controller action that the form should be submitted to, this has nothing to do with javascript functions. – Jerodev Commented Dec 7, 2017 at 15:48 - @Jerodev You re right it was a mistake of me when I was writing the question. I corrected it. – Anastasios Selmani Commented Dec 7, 2017 at 15:56
2 Answers
Reset to default 5The onsubmit
attribute should be returned and return false
to prevent the submitting.
<form id="formId" asp-action="ActionName" onsubmit="return validationFunction(Event)">
If you want to do it "correct" and easiest way set the validation in the class ex:
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; }
}
https://learn.microsoft./en-us/aspnet/core/tutorials/first-mvc-app/validation
Or with JavaScript and even HTML