Reputation: 85
I'm working on ASP.NET MVC4 with Razor, using a model-first Entity Framework connection. I have a Login form made by scratch, that requests for username, password, and Usertype. Unfortunately, the form is able to post even if the fields are blank, which leads to an exception being thrown.
Since I'm directly mapping towards my database through the model instead of using classes on the Models folder, i have no way of applying DataAnnotations. Is there another way to enforce form validation in order to avoid sending null values?
Upvotes: 2
Views: 458
Reputation: 70728
Since you can't use the [Required]
attribute, you probably want to use client side validation. If you're using HTML5
you can mark the fields as required
, you could make a custom helper to output something like the following:
<input id="username" type="text" required />
As demonstrated here (Without the helper method):
You could also validate the user input using JavaScript
manually via.
<input id="username" type="text" />
<button id="submitx" onclick="validate()">Click</button>
function validate() {
var username = document.getElementById("username");
alert(username.value);
if (username.value === "") {
alert('Please fill in the username field');
}
}
Or use a prebuilt library such as jQuery validate
As an additional note it would be best to check these fields at the server level also. Your users may have JavaScript disabled or may deliberately send up malformed information.
Upvotes: 1
Reputation: 1495
In my opinion what you are doing in general is wrong, and counting on client side validation only, is not a good approach since it depends on client side, in MVC, Models are too important and why not using them? by the way i think you should use a ViewModel for your case
Upvotes: 1