[英]Dynamically add javascript for validating phone numbers
我正在研究一個已經上線的項目,現在需要一些修復。 顯然,我需要添加條件javascript / jquery代碼以驗證電話號碼字段。 但是我的問題是,開發人員對電話/電子郵件使用了CommModeID/CommValues
對,對於聯系人的電話/電子郵件也使用了該對。 當CommModeID = 1時,我需要將一個類動態地應用於字段。有人可以在下面的代碼中幫助我如何實現這一點。 現在,我無法理解應該怎么做,因為該項目規模巨大,而且我是這個項目的新手。
模型:
public class ShipperEmail
{
[Key]
public int CommShipperID { get; set; }
public int ShipperContactID { get; set; }
public string Person { get; set; }
public string CommName { get; set; }
[Required(ErrorMessage = "Must be Select")]
public int CommModeID { get; set; }
public string CommMode { get; set; }
[Required(ErrorMessage = "Must be entered")]
public string CommValues { get; set; }
public bool isPrimary { get; set; }
public string flag { get; set; }
public int? RelationID { get; set; }
public int? TimeZoneId { get; set; }
public string PreferredTimeFrom { get; set; }
public string PreferredTimeTo { get; set; }
}
視圖:
@model IList<Writer.Repository.Models.ShipperEmail>
<div class="row">
<div class="col-sm-12"><button type="button" id="btnclose" class="close-link close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div>
</div>
@{ int i = 0; }
@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "frmEditShippercontacts" }))
{
@Html.AntiForgeryToken()
<div class="row mar-none" id="pnl-emailaddresscomps">
<input type="hidden" name="ShipperID" value="@ViewData["ShipperID"]" />
<input type="hidden" name="ShipperContactID" value="@ViewData["ShipperContactID"]" />
<input type="hidden" name="Self" value="@ViewData["Self"]" />
<input type="hidden" name="CommTypeID" value="@ViewData["CommTypeID"]" />
@if (Model != null)
{
for (i = 0; i < Model.Count(); i++)
{
<div class="datarw">
@Html.HiddenFor(m => m[i].ShipperContactID)
@Html.HiddenFor(m => m[i].CommShipperID)
@Html.HiddenFor(m => m[i].flag, new { @id = "flag" })
<div class="row">
<div class="col-sm-4">
@Html.DropDownListFor(m => m[i].CommModeID, new SelectList((System.Collections.IEnumerable)ViewData["SysCommMode"], "Value", "Text", Model[i].CommModeID), new { @class = "form-control input-md" })
</div>
<div class="col-sm-8">
<div class="input-group">
@Html.EditorFor(m => m[i].CommValues, new { htmlAttributes = new Dictionary<string, object> { { "class", "form-control input-md" } } })
@Html.ValidationMessageFor(m => m[i].CommValues, "", new Dictionary<string, object> { { "class", "text-danger" } })
<div class="input-group-btn no-pad">
<div id="Addemailpluse">
<button href="#" class="btn btn-default btn-sm add-btn @(i == 0 ? "btnAddEmail" : "Emailremove-btn") " type="button"><i class="fa @(i == 0 ? "fa-plus" : "fa-minus") "></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3 col-sm-offset-4">
<div class="input-sm pad-none">
<div class="checkbox mar-none">
<label>
@Html.CheckBoxFor(m => Model[i].isPrimary, new Dictionary<string, object> { { "class", "isPrimaryEmail" } }) Primary
</label>
</div>
</div>
</div>
</div>
</div>
}
}
</div>
<div class="row">
<div class="col-sm-2 col-sm-offset-10">
<button type="submit" class="btn btn-primary btn-sm pull-right m-t-sm">@I18N("Save")</button>
</div>
</div>
}
<script>
$(document).ready(function () {
function fnBindEvsAC() {
$('.datarw input[type="checkbox"]').on('change', function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
$('input[type=checkbox]').each(function () {
if (this.checked) {
$(this).prop('checked', false);
$(this).parent('.icheckbox_square-orange').removeClass('checked');
}
});
$(this).prop('checked', true);
$(this).parent('.icheckbox_square-orange').addClass('checked');
} else {
if ($('#pnl-emailaddresscomps .isPrimaryEmail:checked').length == 0) {
$(this).prop('checked', true);
alert("@I18N("Atleast one record should be set as Primary.")");
}
else {
$(this).parent('.icheckbox_square-orange').removeClass('checked');
}
}
});
if ($('#pnl-emailaddresscomps .isPrimaryEmail:checked').length == 0) {
$('#pnl-emailaddresscomps .isPrimaryEmail:first').prop('checked', true);
}
var form = $("#mdlAddEdit form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
}
fnBindEvsAC();
var idxdatarw = "@i";
$('.btnAddEmail').on('click', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var $dr = $('#pnl-emailaddresscomps .datarw').eq(0).clone().find("#hidenemail,#EmailAddress").val("").end();
$dr.find('input,select').each(function () {
this.name = this.name.replace('[0]', '[' + idxdatarw + ']');
this.id = this.id.replace('_0_', '_' + idxdatarw + '_');
var $valmsg = $(this).siblings('.field-validation-valid');
if ($($valmsg).length > 0) {
var stvalmsg = $($valmsg).attr('data-valmsg-for');
$($valmsg).attr('data-valmsg-for', stvalmsg.replace('[0]', '[' + idxdatarw + ']'));
}
});
$($dr).find('input[type="text"],textarea').val("");
$($dr).find('input[type="checkbox"]').prop('checked', false);
$($dr).find('input[id^="flag"]').val('I');
$($dr).find('.btnAddEmail').addClass('Emailremove-btn');
$($dr).find('.btnAddEmail').find("i").removeClass("fa fa-plus").addClass("fa fa-minus");
$('#pnl-emailaddresscomps').append($dr);
fnBindEvsAC();
});
$(document).on("click", ".Emailremove-btn", function () {
if ($(this).closest(".datarw").find('input[type="checkbox"]:checked').length == 1) {
alert('Remove primary then try again..!')
} else {
$(this).closest(".datarw").find('input[id^="flag"]').val('D');
$(this).closest(".datarw").hide();
}
});
$('form#frmEditShippercontacts').on('submit', function (e) {
e.preventDefault();
if (!$(this).valid()) { return; }
$(this).ajaxSubmit({
success: function (data) {
if (data.Success) {
toastr.success("@I18N("Contact detail saved successfully.")");
$('.webui-popover.ShipperContact.in').hide();
if (data.Result.Data) {
var commVal = data.Result.Data.value;
var commtype = data.Result.Data.CommType;
var Self = data.Result.Data.Self;
if (commtype == "@((int)UtilityEnums.SysCommType.Email)") {
if (Self) { $('#selfEmailID').html(commVal); } else { $('#PEmail').html(commVal); }
}
else if (commtype == "@((int)UtilityEnums.SysCommType.Mobile)") {
if (Self) { $('#selfMobile').html(commVal); } else { $('#PMobileupd').html(commVal); }
}
fnReloadMoveSummary();
}
}
else {
$('.webui-popover.ShipperContact.in .webui-popover-content').html(data.Result);
}
btnClosePopups();
},
error: function (e) {
$('.webui-popover.ShipperContact.in').hide();
toastr.error("@I18N("Contact details not saved.")");
}
});
});
});
</script>
控制器:
public ActionResult ShipperDetailsForMove(int id, int asid = 0)
{
ShipperContactPerson data = new ShipperContactPerson();
data = _shipperService.GetShipperCP(id);
if (data.PShipperContactID == null)
{
data.ContactPerson = data.ShipperName;
data.PEMailID = data.EmailId;
data.PMobile = data.Mobile;
}
IEnumerable<Document> DocumentData = _spMoveService.GetDocumentList(id, data.DestinationCountryID == null ? 0 : data.DestinationCountryID, 3);
ViewData["DocumentList"] = DocumentData;
IEnumerable<Communication> CommunicationData = _spMoveService.GetCommunicationData(id).Where(x => x.AccountTypeID == 3);
ViewData["CommunicationData"] = CommunicationData;
ViewData["asid"] = asid;
return View(data);
}
您不能只在輸入上放置模式嗎? 在提交之前對其進行過濾?
即
\+\d{11}
會在沒有國際代碼的情況下響應+614123123等
(\+\d{11})|(\d{10})
會回復0412312312
試試這個方法
function checkPhone(phone) {
return /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(phone);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.