How to validate textbox in MVC3 that must contain string started with characters "PR" - asp.net-mvc-3

i am very much new to MVC3 and working with MVC3 razor application. I need to validate a textbox on View in such a way that, the textbox will accept only those strings which are starting with characters "PR" and 4th character of that string must be "2". It would be great if anybody helps me. Thanks in advance

Well you need regex. I'm not exactly sure what the regex would be and what your string contains. But if you need to have 2 matches in there, you could split it and use 2 textboxes and join the values on post.
ViewModel:
public class MyViewModel
{
[RegularExpression("^PR[A-Za-z0-9]", ErrorMessage= "Invalid Text1")]
public string MyText1 { get; set; }
[RegularExpression("^2[A-Za-z0-9]", ErrorMessage= "Invalid Text2")]
public string MyText2 { get; set; }
}
Warning, this regex may be faulty. I invite others to edit/post comments and i can update it with correct regex
View:
#model MyProject.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.MyText1)
#Html.TextBoxFor(m => m.MyText2)
<button type="submit">Submit</button>
}
Hope this helps

Model
public class RegisterModel
{
public int ID { get; set; }
[RegularExpression(#"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
View
#using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{
<div>
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
}

Related

MVC 5 Conditional Validation Option?

I'm developing an MVC 5 web application. Within a particular View I need to validate a ViewModel, however, I need some of the validation only to occur depending on the users inpupt.
For example, I have a ViewModel
public class TimeEntryViewModel
{
public int proposalID { get; set; }
public int proposalCode { get; set; }
public int nonchargeCode { get; set; }
public SelectList UserProposals { get; set; }
public SelectList TimeEntryClientCodes { get; set; }
public SelectList TimeEntryNonChargeCodes { get; set; }
}
This ViewModel is passed to a View which looks like this
<div class="form-group">
#Html.LabelFor(m => m.proposalID, "Proposal")
#Html.DropDownListFor(m => m.proposalID, Model.UserProposals, "No Proposal", new { #class = "form-control"})
#Html.ValidationMessageFor(m => m.proposalID)
</div>
<div id="ClientCodes" class="form-group" style="display:none">
#Html.LabelFor(m => m.proposalCode, "Client")
#Html.DropDownListFor(m => m.proposalCode, Model.TimeEntryClientCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.proposalCode)
</div>
<div id="NonChargeCodes" class="form-group">
#Html.LabelFor(m => m.nonchargeCode, "Non Charge")
#Html.DropDownListFor(m => m.nonchargeCode, Model.TimeEntryNonChargeCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.nonchargeCode)
</div>
If the user selects 'No Proposal' from the first drop down list, then the drop down list 'nonchargeCode' appears and I need to validate so that the user selects an option from it.
However, if the user selects another option from the first down drop list, then the drop down list 'nonchargeCode' will disappear and another drop down called 'proposalCode' will appear. I then want to validate to ensure the user selects an option from this drop down, but not the 'nonchargeCode' (which will be hidden).
In an MVC 4 application I previously coded, I used http://fluentvalidation.codeplex.com/ to help with this scenario.
I'm just wondering if anyone else had used anything else to overcome this problem of conditional validation? If so, I'd be keen to hear.
Thanks again.
You can use conditional validation in jQuery and in fluentvalidation.
You can use a jQuery selector on the validation, something like this.
I'm not sure about the HTML element names.
$( "#myform" ).validate({ rules: {
proposalCode: {
required: "#proposalCode:visible"
} }
Check out jQuery Dependency expression for more information.
In FluentValidation validation (Server side only) you can use the 'When' expression.
RuleFor(r => r.proposalCode).NotNull().When(e => // Check selected value);
Check out the documentation here
I think this should get you started.

MVC4 client validation not displaying

When I submit my form, The client validation is working, but it is not displaying the error messages for the invalid form fields...
The Model
public class Blog : MainDbContext
{
public int Id { get; set; }
[Display(Name="Author")]
public int Profile { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Title is required.")]
public string Title { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "At least one Tag is required.")]
public string Tags { get; set; }
}
The ViewModel
public class BlogEditViewModel
{
public BlogEditViewModel(Blog blogItem, IEnumerable<SelectListItem> staffList)
{
this.BlogItem = blogItem;
this.StaffList = staffList;
}
public Blog BlogItem { get; set; }
public IEnumerable<SelectListItem> StaffList { get; private set; }
}
The View
<section>
#Html.LabelFor(model => model.BlogItem.Tags)
#Html.EditorFor(model => Model.BlogItem.Tags, null, "Tags")
#Html.ValidationMessageFor(model => model.BlogItem.Tags)
</Section>
The Layout
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
The Output (on form submitted)
<input type="text" value="ok" name="Tags" id="Tags" data-val-required="At least one Tag is required." data-val="true" class="text-box single-line input-validation-error">
<span data-valmsg-replace="true" data-valmsg-for="BlogItem.Tags" class="field-validation-valid"></span>
What i expect is the above Span tag to contain the error message as defined n the Model.
The problem I suspect relates to the naming in the EditorFor, as you can see I use an overload to specify the 'htmlfieldname', as without this the form data fails to map the form fields with the model & fails to save the submitted from data.
If I dont use the overloaded EditorFor, the validation works, but as mentioned above the, the form data fails to map the form fields with the model
how do I get the validation to work?
Thanks
kb
Add this script in your View and client side validation is working fine,
<script src="#Url.Content("~/Script/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Script/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
I think issue is you have to remove null, "Tags"
#Html.EditorFor(model => Model.BlogItem.Tags)
or you have to assign null, "Tags" to
#Html.ValidationMessage("Tags")
Ex:
View
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { Name="asd"})
#Html.ValidationMessage("asd")
Model
public class RegisterModel
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}

Razor view dropdown list for a model class in MVC3

I have two model class in MVC3 one for Services which have those properties
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public int ChildOf { get; set; }
It also have a DB table by Entityframework
Another model is Quata which have those properties
public int ID { get; set; }
public string Sender_Name { get; set; }
public string Description { get; set; }
.....
......
public Services Service_ID { get; set; }
It also have a DB table by Entityframework
I want to create a Razor(C#) view (for Quata) where user can send a quata by fill a html form but where i wanna show a dropdown list with Services ID as dropdown value and Services Name as dropdown text which is also come dynamically from the Services DB table .
My question is how i should create that dynamic dropdown list by #Html.DropDownListFor ? and send the selected data from that dropdown list to a Controller ?
Try this
Controller:
public ActionResult Create()
{
var Services = new Services();
Services.Load(); //load services..
ViewBag.ID = new SelectList(Services.ToList(), "Id", "Name");
return View();
}
[HttpPost]
public ActionResult Create(Quata Quata)
{
//save the data
}
A strong Typed View: (Using Razor)
#model Quata
#using (Html.BeginForm()) {
<fieldset>
<legend>Quata</legend>
<div>
#Html.LabelFor(model => model.Service_ID.ID, "Service")
</div>
<div>
#Html.DropDownList("ID", String.Empty)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
take a look at #Html.DropDownListFor
So say your viewmodel has a list of said Services.
Something that may work for you is the following (you may not need a for loop here, editor is supposed to eliminate that, but I had some weird binding issues).
In your top level view which points at your viewmodel (#model Quata, assuming Quata is your viewmodel) have this code :
#For i = 0 To Model.DropdownListInput.Count - 1
Dim iterator = i
#Html.EditorFor(Function(x) x.DropdownListInput(iterator), "EnumInput")
Next
In your Editor Template (create a subfolder under the view folder this dropdownlist will be in called editor templates and name the template whatever you desire, mine was EnumInput).
In your editor template, which should point at your model for Services (#model Services) have something like the following code (with substitutions for your appropriate variable names):
#<div class="editor-label">
#Html.LabelFor(Function(v) v.value, Model.DisplayName)
</div>
#<div class="editor-field">
#Html.DropDownListFor(Function(v) v.value, New SelectList(Model.ParamEnums, "ValueForScript", "EnumValue"), "--Please Select A Value--")
#Html.ValidationMessageFor(Function(v) v.value)
</div>
Replace the list with your list and the lambda values with yours (#Html.DropDownListFor(x => x.id, New SelectList(x.ServiceList, "ID", "Name"), "--Please Select A Value--") or something like that.
Note that this code is in VB, but it should provide a rough guide.

Editor Template Not working in MVC3

I am trying out the Editor Template in MVC 3
My model class is
public class BookViewModel
{
public int Id { get; set; }
public string Name { get; set; }
[DataType(DataType.Text)]
public string Author { get; set; }
}
I have create a partial view for Editor template and put that in a EditorTemplates folder with name Text.cshtml. following is the partial view
#inherits System.Web.Mvc.WebViewPage<string>
<p> Write the name of author</p> #Html.TextBox(Model)
and I used #Html.EditorFor in the view page
<p> Name : #Html.EditorFor(model => model.Name)</p>
<p> Author</p> #Html.EditorFor(model => model.Author)
But when I run the program what I see is only an empty TextBox. I should see a TextBox filled with Author Name right?
What am I missing here?
Your editor template should be:
#model String
<p> Write the name of author</p> #Html.TextBox("name of the textbox", Model)
The first parameter of the #Html.TextBox() helper can be an empty string as well, but its not recommended

ASP.Net MVC3 Email/Phone Data Annotations don't work

I have the following properties in my Model
[Required]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber
{
get;
set;
}
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
public string EmailAddress
{
get;
set;
}
The corresponding View is
<td>
Email
</td>
<td>
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress, "*")
</td>
</tr>
<tr>
<td>
Phone #
</td>
<td>
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber, "*")
</td>
When I render this page I see the Required attribute getting triggered. But the DataType attribute is not getting fired if I key in Invalid data.I see the source html and don't see any code being emitted for these validations.
I have the following as a part of my view too
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"/>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"/>
You could consider using ASP.NET MVC 3 Futures. Here is a nice article describing validations there:
public class UserInformation
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[Url]
public string Website { get; set; }
[Required]
[CreditCard]
public string CreditCard { get; set; }
[Required]
[FileExtensions(Extensions = "jpg,jpeg")]
public string Image { get; set; }
}
See this post:
Is the DataTypeAttribute validation working in MVC2?
It's important to note that the DataType Attribute is usually used for formatting purposes, not for validation. Technically there are a wide range of email formats and phone number formats (see here for email: http://www.regular-expressions.info/email.html).
Also, custom converters can be made to convert seemingly non-email strings into emails (me at domain dot com = me#domain.com), and thus having default validation regexs flies out the window. It is left up to the developer to use the correct regex for their specific purpose, and to ensure they only accept address they believe are accurate.
Related to this question, there are some third party data validation annotations for download at http://dataannotationsextensions.org/
I just had a similar issue myself. I had the model setup with a data type of email but it was not being validated as an email. I noticed in the html that the view produced the textbox for the email address had a type of text. I then altered my view as below and this fixed it:
#Html.TextBoxFor(m => m.Email, new { type = "email" })
the was using the jquery validate javascript libary

Resources