0

How to validate that user enters string in textbox in asp mvc4? What to write in required tag?

            [required]
Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
Dashang
  • 311
  • 1
  • 3
  • 11

4 Answers4

0

Use the [RegularExpression] attribute if you want to limit the user to only typing in alphabetic characters.

More info on MSDN.

Here is a good link to a regular expression that you can use.

Community
  • 1
  • 1
tobias86
  • 4,979
  • 1
  • 21
  • 30
0

This example maybe helps:

public class CustomerMetaData
{
// Require that the Title is not null.
// Use custom validation error.
[Required(ErrorMessage = "Title is required.")]
public object Title;

// Require that the MiddleName is not null.
// Use standard validation error.
[Required()]
public object MiddleName;

}
Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
  • wll this work?? [Required /^[A-Za-z]+$/] public String Lastname { get; set; } – Dashang Jul 26 '12 at 11:44
  • In that case you should use something like this: `// Allow up to 40 uppercase and lowercase // characters. Use custom error. [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$" ErrorMessage = "Characters are not allowed.")]public object FirstName;` – Pablo Claus Jul 26 '12 at 11:53
0

There are many ways to do it

1) By using plain Javascript or JQuery to check if it has value before submiting the page 2) On controller method check if it has value 3) If you a using EF and your view binded to a model add attribute called [Required]to the property of that model.

Pavan Josyula
  • 1,355
  • 3
  • 13
  • 25
0

What do you actually want to do?

Make sure that the object the server receives has correct data in it? Then you should use data attributes on your C# model. However what do you mean by "enters string"? If the user simply needs to enter any string, then [Required] works - this just means that there has to be some value entered. Do you only want to allow a specific set of characters, like the English alphabet? Then you need to use a RegularExpression attribute.

If you further specify what you actually want to do I am sure we can help you more.

Anders Arpi
  • 8,277
  • 3
  • 33
  • 49