A html page has a text box to enter Employee Name, another text box to input Employee Age and a Save button that when clicked calls a Web API method of SaveEmployeeData
to save data. The Web API is hosted in an asp.net website and all its methods are written in C#.
Question
How would I constrain the end-user to not enter any html or script into the Employee Name and Employee Age text boxes in this situation? I was looking for some attribute that I could apply to these properties in code below. And even if they did input such text, the Web API should respond with validation errors.
//Web API method below
public HttpResponseMessage SaveEmployeeData(EmployeeDetails ed)
{
//code omitted
}
//Type of parameter passed to above Web API method
public class EmployeeDetails
{
[Required]
[StringLength(1000,MinimumLength=10)]
public string FullName { get; set; }
public int Age { get; set; }
}
UPDATE 1
I tried the regular expression suggested by samir, but it appears to not allow even simple alphabet input as shown in screen shot below. The url for this online regex tester is: http://regex.cryer.info/. So think another regular expression needs to be used in this case for Employee Name value.
UPDATE 2
I was able to get the suggested regular expression suggested by samir to work.
The code change I made for allowing alphabets ( any language), digits, single apostrophe, period and dash in my situation is as below. It's the regular expression attribute that I applied to Full Name
property that made sure no html or script was submitted when calling the web api method of SaveEmployeeData
//Type of parameter passed to above Web API method
public class EmployeeDetails
{
[Required]
[StringLength(1000,MinimumLength=10)]
[RegularExpression(@"(^[\p{L} .'-(0-9)]+$)", ErrorMessage = "HTML or Script not allowed")]
public string FullName { get; set; }
public int Age { get; set; }
}