4

I just need example for one validation. For remaining I will do. Let's say I have an input of type text:

 <p>                          
<label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%>         
 </p>        

Here I want to validate textbox for required field. I want this required field validation function in JavaScript and I want to use this script in the view.

9
  • Be a little more clear. What have you done so far? Sample code? Commented Feb 29, 2012 at 10:30
  • i want to write a javascrpt function(for ex:validating a textbox) just like what we do in asp.net.But i want to use tht .js file in MVC3/MVC2. Commented Feb 29, 2012 at 10:40
  • weblogs.asp.net/mikaelsoderstrom/archive/2010/10/06/… something like in the above link. Commented Feb 29, 2012 at 10:43
  • -1 - The question is too brief to allow anyone to help you and shows no effort on your part to try to implement a solution yourself. Commented Feb 29, 2012 at 11:05
  • @Dangerous iam completely new to MVC.so after searching many sites,i culdnt get any solution atleast which may lead to start my work.so i posted here my requirement.how can you tellno effort from my side.i clearly said my reuirement Commented Feb 29, 2012 at 11:18

3 Answers 3

7

Have you considered using unobtrusive validation?

You say you are using MVC3 (although not the Razor view engine apparently).

With your code like this: <p><label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%></p> which could be written as <p>@Html.LabelFor(model=>model.Name) @Html.TextBoxFor(model => model.Name) </p> in Razor syntax.

If you put this in your web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

and then decorate the property in your model with something like this data annotation:

[Display(Name = "Name")]
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }

Then by adding the following into your _Layout.cshtml file you will get unobtrusive validation to work:

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Then you could add this somewhere on the page (where you want the validation message to be shown): @Html.ValidationMessageFor(model=>model.Name)

Sign up to request clarification or add additional context in comments.

4 Comments

yea i would recommend this solution. +1 for very simple explanation.
yeah this solution works fine.but my requirement doesnt have any model.so i cannot use any dataannotations.
you were asking for where to put a unique error msg here it is : [Required(ErrorMessage = "Name is required")]
Thanks Berker Yüceer! @ Santosh: You must have some kind of Model since you have this code in your question model => model.Name. If that's a ViewModel or whatever doesn't matter, you simply add the DataAnnotation to the Name property in there.
2

Try this code.it work on my side you should try:

 <form id="formname" post="" action="">
<ul>
<li>
 <input type="text" name="TimeArrived" id="TimeArrived" class="required" /></li>
 <li><input type="text" name="Name" id="Name" class="required"   />
</li>
 <li>
    <input type="button" name="Save" value="Save" onclick="return Submit();" /></li>
   </ul>
</form>

 $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

 function Submit() {
  var f = $("#formname");

 if (f.valid())
{
}
}

4 Comments

thanks @deepak.i need something like this.but iam writing all my validation functions in one .js file.i want to use that .js file here. function onlyNumbers(evt) { var e = event || evt; // for trans-browser compatibility var charCode = e.which || e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } like this,i have few more function in .js file.i want to use them for "Submit" button
the above code didnt work for me.where are you displaying your errormessages
<script src="@Url.Content("~/Scripts/yourjsfile.js")" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var frm = $("#formname"); frm.validate(); }); function Submit() { var f = $("#formname"); if (f.valid()) { } } </script> just copy paste this to your view and change yourjsfile.js with your js file name.. He already answered well enough also @Deepakmahajan +1 for the effort and only true answer.
@BerkerYüceer thanks for the reply.The above way is not working for me.can u please give with some elaborate example. I need a requiredfieldvalidation for the following textbox <p> <label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%> </p> some javascript function to validate on button click. Thanks in advance
1

Now <%= Html.TextBoxFor(model => model.Name)%> is the key here u should give an ID to each of your elements that you want to use validation on..

so its gonna look like;

<%= Html.TextBoxFor(model => model.Name,new { id="ClientNameTxt"})%>

if you already defined some scripts (.js files) and want to implement to this view then use

<script src="@Url.Content("~/Scripts/yourjsfile.js")" type="text/javascript"></script>

and use ur functions to validate or else write new script

<script type="text/javascript">
    $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

    $('#formname').Submit(function (event) {
        /* Call ur form with the id you have given */
        var f = $("#formname");

        if (f.valid()) {  /* When the form is valid */

        } else {  /* When the form is not valid */
            event.preventDefault(); /* Prevent from submitting the form */
            $("#ClientNameTxt").highlight(); /* Do some validation stuff on ur validation required element */
        }
    });
</script>

at the end it will look like;

                 <!--Your form name, Controller name-->         
@using (Html.BeginForm("Formname", "ControllerName", FormMethod.Post,new { id="Formname", onkeypress="return event.keyCode != 13;"}))
{
    <p> 
        <label for="ClientName">ClientName:</label> <!--Give an ID to your element-->
        <%= Html.TextBoxFor(model => model.Name, new { id="ClientNameTxt" })%>
    </p>
}

<script type="text/javascript">
    $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

    $('#formname').Submit(function (event) {
        /* Call ur form with the id you have given */
        var f = $("#formname");

        if (f.valid()) {  /* When the form is valid */

        } else {   /* When the form is not valid */
            event.preventDefault(); /* Prevent from submitting the form */
            $("#ClientNameTxt").highlight(); /* Do some validation stuff on ur validation required element */
            $("#Formname").append('<ul><li> Fill the empty areas and try again. <li><ul>');
            /* This is the worst i can do. Just to let you understand it easly. */
        }
    });
</script>

if u still have problems with this issue! i guess ur solution is at training your self with the --> jquery

2 Comments

howto/whereto write error messages.iam new to Jquery. and what about button "Submit".I place a button and should there be any return for that
as you can see i ve added a highlight to that input! you can use a similar way and put some error msg. im going to update the answer look carefully at the else { } section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.