我正在尝试使用jQuery的validate插件来更改用户名。我设法使用远程选项来检查我的数据库中是否找到了用户名。以下是我的工作示例。但是,如果示例表单中的Peter未更改其名称,则该字段无效,因为该名称已在数据库中。我不知何故需要包含条件 - 如果#new_name与#current_name相同,则#new_name字段有效。有可能吗?
jQuery Validation Plugin
<script type="text/javascript">
$(document).ready(function(){
$("form").validate({
rules: {
new_name: {
required: true,
remote: {
url: "names.php",
type: "post",
}
}
},
messages: {
new_name: {
remote: jQuery.validator.format("{0} is already taken, please enter a different name.")
}
}
});
});
</script>
HTML表单:
<form method="post" id="myForm" action="">
<!-- User enters a new name -->
<input id="new_name" name="new_name" value="peter" type="text" />
<!-- This is a current username, populated from the database -->
<input id="current_name" name="current_name" value="peter" readonly="readonly" />
<input type="submit" name="submit" id="submit"/>
</form>
远程呼叫:names.php
<?php
$request = trim(strtolower($_REQUEST['new_name']));
// Here is the array of all user names in my database.
$names = array('peter','jane','bill','george');
$valid = 'true';
foreach($names as $name) {
if( strtolower($name) == $request ) {
$valid = 'false';
}
}
echo $valid;
?>
答案 0 :(得分:0)
我认为你应该这样做(服务器端)
$request = trim(strtolower($_REQUEST['new_name']));
// Here is the array of all user names in my database.
$names = array('peter','jane','bill','george');
$valid = true;
foreach($names as $name) {
if( strtolower($name) == $request ) {
$valid = false;
}
}
echo json_encode($valid);
答案 1 :(得分:0)
rules: {
new_name: {
required: true,
remote: {
url: "names.php",
type: "post",
data: current_name: function () {
return $('current_name').val();
new_name: function () {
return $('new_name').val();
}
}
}
},
答案 2 :(得分:0)
您没有根据新名称检查当前名称。
试试这个:
<?php
$request = trim( strtolower( $_REQUEST['new_name'] ) );
$old = trim( strtolower( $_REQUEST['current_name'] ) );
// Here is the array of all user names in my database.
$names = array( 'peter', 'jane', 'bill', 'george' );
$valid = 'true';
if ( $request == $old ) {
$valid = "true";
} else {
foreach ( $names as $name ) {
if ( strtolower( $name ) == $request ) {
$valid = 'false';
}
}
}
echo $valid;
?>
现在,如果名称未更改,则返回true,仅在更改时执行exists检查。