Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add validators for @Html.TextBox() without model

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?

like image 951
Bhavin Bhaskaran Avatar asked Jun 15 '15 07:06

Bhavin Bhaskaran


1 Answers

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.
like image 182
ramiramilu Avatar answered Nov 09 '22 23:11

ramiramilu