c# - How to Create Custom "type" attribute for textboxfor in Asp.net MVC? -
i working in mvc. have stuck badly in situation. know,
@html.textboxfor
have property named type detects type of input textbox can take.
for ex: type = "email" takes email input , if validation fails shows error message "please enter valid email address".
type = "number" takes number input , shows validation message if text use.
i want textbox take mobile/phone numbers(with country codes , without country codes well. e.g. +9177777777777).
so can create own custom "type" attribute can accomplish above task , can generates own validation message if validation fails ?
the attribute type
talking attribute of <input />
html element. per html5 specifications there several valid values attribute can take. see them here: http://www.w3schools.com/html/html5_form_input_types.asp
so, cannot add sort of "custom" value imply automatic validation browser. want, think, able validate input against specific phone number format. need use [regularexpression]
attribute (entirely different thing, named same) on property in model class. this, coupled unobtrusive client side validation, give behaviour want.
update
different values of type
attribute enable invoke browser's native client side validation support. custom formats, use general type="text"
, put regular expression in pattern
attribute. browser display error popup message title
attribute.
so, in view have this:
@html.textboxfor(m => m.phonenumber, new { pattern = "\d{3}-\d{3}-\d{4}" })
assuming property name phonenumber
. regular expression different depending on actual format want support.
i think it's worth mentioning couple of attributes related validation:
required
maxlength
more native client side validation here: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/