2013-10-08 14 views
2

我正在爲我的MVC項目中的電子郵件ID和確認電子郵件ID使用2個文本框。如何在移動到下一個文本框之前強制用戶輸入有效的電子郵件?

上查看:

@Html.TextBoxFor(m => m.Email, new { maxlength = 50, title = "Enter Email" }) 
@Html.ValidationMessageFor(m => m.Email) 
@Html.TextBoxFor(m => m.ReEmail, new { maxlength = 50, title = "Confirm Email" }) 
@Html.ValidationMessageFor(m => m.ReEmail) 

上查看型號:

[DisplayName("Email")] 
    [Required(ErrorMessage = "Please enter Email")] 
    [RegularExpression(RegexTypes.EMAIL, ErrorMessage = RegexTypes.EMAIL_MESSAGE)] 
    public string Email { get; set; } 

    [DisplayName("Confirm Email")] 
    [Required(ErrorMessage = "Please re enter Email")] 
    [RegularExpression(RegexTypes.EMAIL, ErrorMessage = RegexTypes.CONFIRM_EMAIL_MESSAGE)] 
    [DataType(DataType.EmailAddress)] 
    [System.Web.Mvc.Compare("Email", ErrorMessage = "The email and confirmation email does not match.")] 
    public string ReEmail { get; set; } 

它工作正常,並顯示該消息。

我想停止用戶,如果電子郵件是無效的,那麼用戶不應該能夠在第二個文本框中輸入確認電子郵件,直到電子郵件不正確。怎麼做?有人請幫助我。

回答

1

如果電子郵件無效,您可以添加自定義jQuery,以在確認文本框爲焦點時重新聚焦電子郵件文本框。

$("#confirmTextBox").focusin(function() { 
    if (!emailIsValid()) 
    { 
     $("#emailTextboxID").focus(); 
    } 
}); 

其中emailIsValid()是您自己的方法。

如果您想要更多地阻止用戶的操作,可以在郵件文本框的模糊處執行此操作(這意味着在電子郵件有效之前,他無法在頁面上集中其他任何內容)。

$("#emailTextboxID").blur(function() { 
    if (!emailIsValid()) 
    { 
     $(this).focus(); 
    } 
}); 

最後,您還可以禁用tab鍵:

//disable the tab key 
$(document).keydown(function(objEvent) { 
    if (objEvent.keyCode == 9) { //tab pressed 
     objEvent.preventDefault(); // stops its action 
    } 
}) 
0

這只是一個提示:

@Html.TextBoxFor(m => m.Email, new { maxlength = 50, title = "Enter Email", onblur="regainFocusOnError()" }) 

[編輯]剛跑到一個快速測試和它的作品。絕招這裏是檢查由助手生成輸入驗證類,如果它出現在輸入重新獲得焦點:

@Html.TextBoxFor(m => m.UserName, 
new { maxlength = 50, title = "Enter Email", onblur="var me = this; setTimeout(function() { if($(me).hasClass('input-validation-error')) { me.focus(); } }, 0);" }) 
+0

什麼是regainFocusOnError()? – Rocky

+0

你自己的js在.focus()函數中使用,最後可能是.select()。可以寫整個js行,雖然 – Max

+0

讓我們說:onblur =「var me = this; setTimeout(function(){if(!isEmailValid()){me.focus();}},0);」 – Max

0

假設你正在使用jQuery.validate,你可以封裝在自己的驗證功能。請注意,這段代碼會觸發你頁面上的所有經過驗證的jQuery驗證郵件。

$(function() { 
    // track original validation method 
    var originalMailValidator = $.validator.methods.email; 

    var keepFocus = function() { 
     var that = this; 
     setTimeout(function() { that.focus(); }, 0); 
    }; 

    // encapsulate the original validation function in custom 
    // function which keeps focus 
    $.validator.methods.email = function(value, element) { 
     $(element).unbind('blur', keepFocus); 
     var result = originalMailValidator.apply(this, [value, element]); 
     if (!result) 
      $(element).bind('blur', keepFocus); 
     return result; 
    }; 
}); 
相關問題