单个字段的Jquery验证

时间:2013-06-20 08:16:23

标签: c# jquery

我的表单是

  @using (Html.BeginForm("Create", "Account", FormMethod.Post, new { @class = "CreateUser" ,id="createform"}))
 { 
  @Html.ValidationSummary();
<div class="field"><label>User Name*</label></div><input name="UserName" type="text" />
<div class="field"><label>Name</label></div><div class="field1"><input name="FirstName" type="text" placeholder="First Name"/><input name="Middlename" type="text" placeholder="Middle Name" /><input name="LastName" type="text" placeholder="Last Name" /></div>
<div class="field"><label>Email*</label></div><input name="Email" type="text" />
<div class="field"><label>Mobile*</label></div><div class="field2"><input name="CountryCode" type="text" placeholder="Country Code" /><input name="Mobile" type="text" placeholder="Mobile Number" /></div>
<div class="field"><label>Language</label></div><input name="Language" type="text" />
<div class="field"><label>Expiry Date*</label></div><input name="Expiry" type="text" id="datepicker" />

<input id="send" class="subbtn" type="submit" value="Create"/>

如何使用jQuery仅验证用户名字段?

3 个答案:

答案 0 :(得分:0)

如果你需要字段验证器,你可以使用这样的东西(JS):

<input name="UserName" type="text" id="UN"/>

var textBox = document.getElementById('UN');
if(textBox=='')
   //your error message

答案 1 :(得分:0)

看起来您希望将用户名设为必填字段。如果是这样,您需要将以下属性添加到您的用户名输入控件:

<input name="UserName" type="text" data-val="true" data-val-required="User name field is required."/>

此外,您还需要配置不显眼的验证,链接如何执行:http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

答案 2 :(得分:0)

$(document).ready(function(){

  $('#createform').submit(function(){
    var user_name = $('input:first').val();
    if(user_name == /*whatever you want to test*/){
     //doesn't pass test
     this.preventDefault();
     alert("Username error");
    } else {
     this.submit();
    }
  });

});