Validation in Model-first Entity framework application

443 views Asked by At

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?

2

There are 2 answers

0
Darren On

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):

http://jsfiddle.net/ck4dL/

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.

2
Milad Hosseinpanahi On

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