Reputation: 161
Trying to validate my Phone Number so no one can input random letters inside the input box. I do have the unobtrusive and validate scripts. So far I have tried a few things inside my Model,
[RegularExpression(@"^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$", ErrorMessage = "Not a valid Phone number")]
[Display(Name = "Phone")]
public string SMSPhoneNumber;
or
[DataType(DataType.PhoneNumber)]
public string SMSPhoneNumber;
This is my View
<form role="form" action="#">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="control-label"><b>Phone Number</b></label>
@Html.TextBoxFor(model => model.SMSPhoneNumber, new {@class = "form-control", @placeholder = "Enter Phone Number", @id = "phoneNumber", Name = "phoneNumber", data_val_required = "Please enter a phone number"})
@Html.ValidationMessageFor(model => model.SMSPhoneNumber, null, new { @class = "text-danger" })
</div>
<button type="button" data-dismiss="modal" class="btn dark btn-outline"> Cancel</button>
<button type="button" data-toggle="modal" id="" class="btn green" onclick="javascript: updateDatabase();">Submit</button>
</form>
This is my controller
[HttpPost]
public ActionResult UpdatePhoneNumber(string phoneNumber)
{
if (ModelState.IsValid)
{
return View();
}
}
The validation is still not working, what could be the issue?
Thanks
Upvotes: 3
Views: 73
Reputation:
The reason your do not get client side validation is that you have changed the name
attribute by using new { Name = "phoneNumber" }
and you have not created a validation message placeholder for phoneNumber
(just one for SMSPhoneNumber
).
Under no circumstances should you ever change the name
attribute. Nor should you be adding data-val-*
attributes (and its not clear why your changing the id
attribute). The HtmlHelper
methods will always generate the correct html for model binding and validation when used correctly.
The reason you do not get any server side validation is that your not binding to your model, just to a string
.
Change the view code to
@Html.TextBoxFor(m => m.SMSPhoneNumber, new { @class = "form-control", placeholder = "Enter Phone Number" })
@Html.ValidationMessageFor(m => m.SMSPhoneNumber, null, new { @class = "text-danger" })
and change the POST method to receive your model (assuming its say public class Company
), then
[HttpPost]
public ActionResult UpdatePhoneNumber(Company model)
Upvotes: 2