how to write validation error
Loading
how to write validation error
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh KumarPosted Jul 17, 2023, 9:47 AM
please refer below one,
https://www.c-sharpcorner.com/article/validation-message-and-validation-summary-in-asp-net-mvc/
https://www.tutorialsteacher.com/mvc/htmlhelper-validationmessagefor
Praveen MishraPosted Jul 14, 2023, 9:27 AM
1. Using Validation Controls:
ASP.NET provides built-in validation controls that you can use to display validation errors. You can place these controls on your web form and customize their error messages. Some commonly used validation controls include:
- RequiredFieldValidator: Ensures that a specific input field is not left empty.
- RangeValidator: Checks if the input falls within a specified range of values.
- RegularExpressionValidator: Validates the input against a specified regular expression pattern.
- CustomValidator: Allows you to define custom validation logic.
To display validation errors using these controls, follow these steps:
a. Add the required validation control to your web form, specifying the validation logic and error message.
b. Set the `ErrorMessage` property of the validation control to the desired error message.
c. Associate the validation control with the input control you want to validate using the `ControlToValidate` property.
d. When the validation fails, the error message will be displayed automatically.
2. Using ModelState:
In ASP.NET MVC, you can use the `ModelState` object to store and display validation errors. This approach allows you to perform server-side validation and display the errors next to the corresponding input fields. Here's an example:
In your view, you can display validation errors using the `ValidationMessageFor` helper method:
Make sure you have included the necessary validation attributes (e.g., `[Required]`, `[Range]`, etc.) on your model properties.
3. Manual Validation:
You can manually validate input in your code-behind or controller and add validation errors to the `ModelState` object. This approach gives you more flexibility but requires additional code. Here's an example:
In your view, you can display manual validation errors using the `ValidationSummary` helper method:
These are some common approaches to writing validation errors in ASP.NET. The specific method you choose depends on your application's architecture and requirements.