2

I have the following properties in my data model:

[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }

My textbox currently have a place holder in them so that when they focus on the textbox the place holder will disappear inside the textbox, if they don't type anything in then the text box val ($(textbox).val()) is eqaul to "First Name" or "Last Name", how can I check for this so that an error will be returned in my validation saying "Please fill out first name/last name" if the FirstName or LastName is equal to "First Name" and "Last Name"

anthonypliu
  • 12,179
  • 28
  • 92
  • 154

1 Answers1

6

You should write your own ValidationAttribute and use it on your properties

Simple Example:

public sealed class PlaceHolderAttribute:ValidationAttribute
{
    private readonly string _placeholderValue;

    public override bool IsValid(object value)
    {
        var stringValue = value.ToString();
        if (stringValue == _placeholderValue)
        {
            ErrorMessage = string.Format("Please fill out {0}", _placeholderValue);
            return false;
        }
        return true;
    }

    public PlaceHolderAttribute(string placeholderValue)
    {
        _placeholderValue = placeholderValue;
    }
}

Use it on your property like this:

[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
[PlaceHolder("First Name")]
public string FirstName { get; set; }
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38