I have a form where the user can update his name and last name. I use jQuery validation to validate the form. How can I validate if the user put spaces?
我有一个表单,用户可以更新他的姓名和姓氏。我使用jQuery验证来验证表单。如何验证用户是否放置空格?
here's what i have:
这就是我所拥有的:
<script>
$(document).ready(function(){
$('#submit').click(function() {
var valid = $("#myform").valid();
if(!valid) {
return false;
}
$.ajax({
type: "POST",
url: 'save',
data: $('#myform').serialize(),
dataType: 'json',
cache: false,
success: function(result) {
// redirect to another page
}
});
});
});
</script>
</head>
<body>
<form id="myform" method="post" action="">
<fieldset>
<legend>update name</legend>
<p>
<label for="fname">Name</label>
<em>*</em><input id="fname" name="fname" size="25" class="required" minlength="2" />
</p>
<p>
<label for="lname">Last Name</label>
<em>*</em><input id="lname" name="lname" size="25" class="required" minlength="2" />
</p>
<p>
<input id="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
thanks
谢谢
1 个解决方案
#1
31
use this for your javascript code:
将此用于您的JavaScript代码:
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "Space are not allowed");
$("#myform").validate({
errorLabelContainer: $("#error"),
rules: {
fname: { required: true, noSpace: true },
lname: { required: true, noSpace: true }
},
messages: {
fname: { required: 'Please enter your name' },
lname : { required: "Please enter your last name" }
}
});
$('#submit').click(function() {
var valid = $("#myform").valid();
if(!valid) {
return false;
}
$.ajax({
beforeSend: function() {
// display loading message
},
type: "POST",
url: 'save',
data: $('#formdata').serialize(),
dataType: 'json',
cache: false,
success: function(result) {
if(result.error) {
// show error message
}
else {
// redirect to another page
}
},
error: function (response, desc, exception) {
// show ajax error
},
complete: function() {
// hide loading message
}
});
});
});
#1
31
use this for your javascript code:
将此用于您的JavaScript代码:
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "Space are not allowed");
$("#myform").validate({
errorLabelContainer: $("#error"),
rules: {
fname: { required: true, noSpace: true },
lname: { required: true, noSpace: true }
},
messages: {
fname: { required: 'Please enter your name' },
lname : { required: "Please enter your last name" }
}
});
$('#submit').click(function() {
var valid = $("#myform").valid();
if(!valid) {
return false;
}
$.ajax({
beforeSend: function() {
// display loading message
},
type: "POST",
url: 'save',
data: $('#formdata').serialize(),
dataType: 'json',
cache: false,
success: function(result) {
if(result.error) {
// show error message
}
else {
// redirect to another page
}
},
error: function (response, desc, exception) {
// show ajax error
},
complete: function() {
// hide loading message
}
});
});
});