6

This is a part of my view

@model bhavin.Models.Employee

@using (Html.BeginForm("BuynowForm", "Home"))
{
<div class="form-group">
   <label>Billing Address</label>
   @Html.TextBox("bill_address", null, new { @class = "form-control valid" })
</div>
<p>
<input type="submit" value="Submit" class="btn btn-primary" />
</p>
 }

I want to add required validation to it. The billing_address textbox is not a part of the models.employee. I am using mvc5 So how to add the validator?

5
  • Use a view model that includes all the properties your need. Commented Jun 15, 2015 at 7:20
  • 1
    try by adding data-* attributes as how here - @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" }). Do not forget to add unobtrusive and validate JS files. Commented Jun 15, 2015 at 7:26
  • @ramiramilu It worked..Thank you. But where I can print the "Billing Address is required" message? It is not coming. I am new to mvc. Commented Jun 15, 2015 at 7:33
  • 1
    use @Html.ValidationSummary() Can I post this as an answer? Commented Jun 15, 2015 at 7:34
  • Yes. you should actually. pleas include validationsummary() details also. It worked perfectly for me. Thank you... Commented Jun 15, 2015 at 7:36

2 Answers 2

11

Add data-val and data-val-required attribute for Html.TextBox() as shown below.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>    

@using (Html.BeginForm("",""))
{
    @Html.ValidationSummary()
    @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" })
    <input type="submit" value="Click" id="btnSubmit" />
}

NOTE

  1. @Html.ValidationSummary() is used for printing validation message.
  2. Do not forget to include - validate and unobtrusive JavaScript files.
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly for me. Thanks for the support . If you can share some links to know other properties like @data_val_required , (can be string minimum length) , it will be a great help.
0

Don't know if it's what you're looking for, but look a this :

In your BuynowForm method, add a string parameter called bill_address.

On the form submit, you'll get the input value in this string, and you'll be able to make your validations.

Hope this helps

1 Comment

Actually i was looking for something else and marked one reply as the answer to the question. Thanks for the reply

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.