我正在使用 Alloy UI 和 YUI3 并且有一个表单,根据从选择下拉列表中的用户选项选择,它会触发对服务器的 ajax 调用。服务器返回我发送到 AUI-Form-Validation 模块的新验证规则。规则正在改变,但表单正在输出重复的规则。也就是说,不替换表单验证实例,而是附加到旧的,所以我在浏览器中有重复的错误字段字符串。我认为我需要销毁所有实例,但最新的但似乎无法实现这一点。如何销毁/更新旧的表单验证,以便我只在 DOM 中显示最新的表单?
这是我的代码(我在本地测试时使用 on.failure):
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://cdn.alloyui.com/2.5.0/aui-css/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<form id="myForm">
<select id="card-type" name="card-type" class="select_card_type">
<option value="7" selected="selected" label="Seven"></option>
<option value="2" label="Two"></option>
<option value="5" label="Five"></option>
</select>
<div class="control-group card_number">
<label class="control-label" for="cardNumber">Card number</label>
<div class="controls">
<input name="cardNumber" id="cardNumber" type="text" />
</div>
</div>
<div class="control-group csc">
<label class="control-label" for="picture">Card security code</label>
<div class="controls">
<input name="csc" id="csc" type="text">
</div>
</div>
<input class="btn btn-info" type="submit" value="Submit">
</form>
</div><!--/span-->
</div><!--/row-->
<hr>
<footer>
<p>© Company 2013</p>
</footer>
</div><!--/.fluid-container-->
<script src="http://cdn.alloyui.com/2.5.0/aui/aui-min.js"></script>
<script>
YUI().use('node', 'node-base', 'event', 'transition', 'aui-io-request', 'json-parse', 'aui-form-validator', function(Y) {
var rules;
function Validator(rules) {
this.rules = rules;
this.fieldStrings = {
cardNumber: {
required: 'Type your card number in this field.'
},
csc: {
required: 'Please provide your csc.'
}
};
this.val = new Y.FormValidator(
{
boundingBox: '#myForm',
fieldStrings: this.fieldStrings,
validateOnInput: true,
rules: this.rules
}
);
}
Y.one('.select_card_type').on('change', function(e) {
var len = Y.one('#card-type option:checked').get('value');
Y.io.request('<%= selectProductTypeResource.toString() %>', {
method: 'post',
on: {
failure: function() {
rules = {
cardNumber: {
required: true,
digits: true,
minLength: len,
maxLength: len
},
csc: {
required: true,
digits: true,
minLength: len,
maxLength: len
}
};
if (typeof (validator) === 'object') {
validator.val.destroy(true); // not working
}
validator = new Validator(rules);
}
}
});
});
});</script>
</body>
</html>