Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I"m using asp.net MVC 4 form validations inside using script for validation alerts.its working fine,but i declared required in model for particular field,its not working.

Now what i want is need to display required msg near textbox. that's it

What I have tried:

Model
[Required(ErrorMessage = "Please Enter Instagram Name")]
      [Display(Name = "Enter First Name")]
      [StringLength(50, MinimumLength = 3, ErrorMessage = "First Name must be between 3 and 50 characters!")]
      public string instagramhandle { get; set; }

Controller for displaying alerts
if (res == 0)
                {
                    string emailRegex = @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";
                    string phoneRegex = @"^\d{10}$";


                    Regex re = new Regex(emailRegex);
                    if (!re.IsMatch(EmailId))
                    {
                        Message = "Emailfailed";
                        return Json(Message, JsonRequestBehavior.AllowGet);
                        // ModelState.AddModelError("Email", "Please Enter Correct Email Address");
                    }

view

<form method="POST">

       <script>
       $(function () {
           $("#dialog").dialog();
       });
       $('#btnpsubmit').hide();
       $(function () {<pre>    $('#btnpsubmit').click(function () {

                       if (whichTime == 1) {

                           var firstname = $('#id_firstname').val();
                           var lastname = $('#id_Lastname').val();
                           var phoneno = $('#id_Phonename').val();
                           var handlename = $('#id_Instagram').val();
                           var EmailId = $('#id_EmailId').val();
                           var password = $("#id_passwordregister").val();

                           if (($('#id_firstname').val().length > 0) && ($('#id_Instagram').val().length > 0) && ($('#id_passwordregister').val().length > 0) && ($('#id_EmailId').val().length > 0) && ($('#id_Lastname').val().length > 0) && ($('#id_Lastname').val().length > 0) && ($('#id_Phonename').val().length > 0))

                               $.post("/Registration/Registration", {
                                   handlename: handlename,
                                   EmailId: EmailId,
                                   firstname: firstname,
                                   lastname: lastname,
                                   phoneno: phoneno,
                                   password: password

                               }).done(function (data) {

                                   if (data == "success") {
                                       //alert("Inserted Successfully!");
                                       location.href = '//' + window.location.host + '/home/plans';
                                   }
                                   if (data == "failed") {
                                       //location.href = '//' + window.location.host + '/home/plans';
                                       alert("Data Failed to insert!");
                                   }
                                   if (data == "Emailfailed") {
                                       //location.href = '//' + window.location.host + '/home/plans';
                                       alert("Please Enter Correct Email Address!");
                                   }
Posted
Updated 3-Aug-17 3:49am

You can make the data annotations validators work on the client side quite easily:
  1. Add a reference to the Microsoft.jQuery.Unobtrusive.Validation[^] NuGet package;
  2. Add the settings to your web.config file:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <appSettings>
            <add key="ClientValidationEnabled" value="true" />
            <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        </appSettings>
    </configuration>

    OR: Enable the validation via code:
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
  3. Make sure you have the "jqueryval" bundle defined:
    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
        "~/Scripts/jquery.validate.js",  
        "~/Scripts/jquery.validate.unobtrusive.js"));
  4. Output the "jqueryval" bundle on any view that requires it:
    @section Scripts {  
        @Scripts.Render("~/bundles/jqueryval")  
    }
  5. Add a validation summary to your form:
    @Html.ValidationSummary()
  6. Display the validation errors next to each field:
    @Html.ValidationMessageFor(m => m.FieldName, "*")

Your form will now automatically validate on the client based on the supported attributes. You can also create your own custom validation attributes with client-side support, or you can use remote validation to call a server-side validation method from the client-side validator.

ASP.NET MVC 5 - JQuery Form Validator[^]
The Complete Guide To Validation In ASP.NET MVC 3 - Part 1[^]
The Complete Guide To Validation In ASP.NET MVC 3 - Part 2[^]
How to: Implement Remote Validation in ASP.NET MVC[^]
 
Share this answer
 
v2
Adding these attributes is only really useful for validating the model when it's posted back into the controller. They don't do anything on the front-end unless you're using the unobtrusive validation (which was always a bit clunky).

If you want front-end validation, you're better off using HTML attributes, for example:
<input type="text" id="id_firstname" maxlength="50" required pattern=".{3,50}" title="Enter a valid name" />

Make your form method "post" and have your button type set as "submit" and everything should work from there. Don't forget to validate your model object when it's posted into the controller too.
 
Share this answer
 
v2
Comments
Richard Deeming 3-Aug-17 9:50am    
Unobtrusive validation isn't particularly clunky, at least in recent versions. :)
[no name] 3-Aug-17 9:52am    
Maybe it was just me that didn't like it much :) It also doesn't work in the current world of SPA apps, whereas HTML validation does (Angular, etc).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900