I having a MVC3/Razor form with a dropdown and a single text box. Dropdown has 2 options to choose either OrderID or ClerkName.
If user choose OrderID, then I want to accept only numbers [0-9] into textbox 开发者_JAVA百科and if user choose ClerkName, then I want to accept only characters [a-z, A-Z] into textbox.
I want here jQuery validaton..please help me in this direction.
Here we need to check validation in both case, 1. on form load and 2. on DDL selction change.....please help.
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
<div id="mainP">
<div>
@Html.DropDownList("SearchBy", new[] { new SelectListItem { Text = "Order ID", Value = "OrdId" },
new SelectListItem { Text = "Clerk Name", Value = "ClerkName" } })
<br />
@Html.TextBox("SearchedText", ViewData["SEARCHED_TEXT"] == null ? "" : ViewData["SEARCHED_TEXT"], new { @class = "search_text_area" })
<br />
</div>
<input type="button" id="btnSubmit" value="Submit" />
</div>
}
<script type="text/javascript">
$(function () {
});
</script>
I'm assuming you really want to: clear the input on selection change (since by your validation rules, its no longer valid) and validate on submit, not form load.
$(function(){
// Get a reference to the controls we'll re-use throughout the program
var searchedText = $("#SearchedText");
var searchBy = $("#SearchBy");
// Determine the validation regular expression
function GetValidationRegex(){
if (searchBy.val() == "OrdId")
return /^[0-9]+$/;
else
return /^[a-zA-Z ]+$/;
}
// Define our on change handler
function SearchByChangeHandler(){
// Clear the input
searchedText.val("");
}
// Bind the handler
$("#SearchBy").change(SearchByChangeHandler);
// Bind to the form submit to validate
$("form").submit(function(){
// Get the text
var value = searchedText.val()
// If no text, error case 1
if (!value){
alert("A value is required...");
return false;
}
// If doesn't match the validation expression for the current selection
// this is your error case
else if (value.match(GetValidationRegex()) == null){
alert("Regex doesn't match...");
return false;
}
});
});
You'd have to create a custom validation rule:
jQuery.validator.addMethod("numbersXorLetters", function(value, element) {
var isValid = false;
if($("#SearchBy").val() == "OrdId")
isValid = /^[0-9]*$/.test(value);
if($("#SearchBy").val() == "ClerkId")
isValid = /^[a-zA-Z]*$/.test(value);
return this.optional(element) || isValid;
}, "Invalid value");
And then applying this like so:
$("#SearchBy").rules("add", {
numbersXorLetters: true
});
Hope this helps. Cheers
精彩评论