I need to validate an input field value from user before the form is submitted.
I have created an action in my custom controller and decorated the field with it:
action name: CheckValue
controller name: Validate
[Remote("CheckValue", "Validate"), ErrorMessage="Value is not valid"]
public string Value { get; set; }
The problem is when I press submit, the form is being submitted and then the message Value is not valid
is shown if the value entered by the user is not valid.
How can I validate the value entered by user and prevent the form to be submitted if value is not valid, and display the error message?
If I try in JavaScript to check if the form is valid $("#formId").valid()
that returns true, that means no matter what is the status of the value (valid or not) the form is valid.
In the other hand if I decorate another field with the [Required]
attribute the form is not submitted and the error is shown for that field that is required. However the validation doesn't occur behind the scene for the remote validation field.
The complete solution of Remote Validation in MVC. It will check if the email exists in database and show the following error:
Account Controller Action
Add Model Validation
Add Scripts
Yes, you have to add
[Remote]
to your model:And Controller:
Works for me fine; I hope will useful for you.
With the reference of c-sharpcorner demo
We can use RemoteAttribute.
Step 1
In the HomeController create a method and for that write the following.
You might be wondering why we are returning JsonResult back. We want the validation to occur at the client side, so we are returning a JsonResult.
Step 2
The next step is to hook this method up with the username property and for that first we need to add a class file in the models folder, add a partial User class and provide the required customization to the UserName property.
Step 3
In create.cshtml we need to specify the source of the three jQuery files in the given order.
You dont put the Controller code. But must to be something like this:
Your code:
My code for the controller(Validate):
The existing answers are great but there are a couple of gotchas:
1) The validation method's parameter name has to exactly match the name of the property being validated, e.g. for
The validation method's parameter must be called
DocumentTypeCode
, including the capital letter, or else you'll get a null as the parameter instead of the value of the property being validated:Be particularly wary of this if you are a Resharper user, of if you're writing multipurpose validation methods for use by more than one property.
2) I had to get this working with a Telerik grid and I had to implement it slightly differently in order to get the validation failure messages to show correctly in the grid (the examples here showed 'false' as the validation error message):