因此。我正在尝试使用ajax创建字段验证。我已经在必要的验证字段上创建了类“validate-field”。
One Field是email_addres,另一个是taxvat。在我的控制器上,我刚刚创建了一个动作“验证”,然后我尝试获取字段ID和字段值。
请遵循以下代码:
- jQuery:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".continuar").on("click", function(){
url = "<?php echo Mage::getUrl('awmajax/ajax/validar')?>";
jQuery(".required-entry").each(function(){
if(jQuery(this).val() == ""){
jQuery(this).addClass("validation-failed");
}
else {
jQuery(this).removeClass("validation-failed");
}
});
jQuery(".validate-field").each(function(){
fieldName = jQuery(this).attr('id');
fieldValue = jQuery(this).val();
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
data: ({
field : fieldName,
value : fieldValue
}),
success: function(result){
console.log(result);
}
});
});
});
});
</script>
和php:
public function validarAction(){
$params = $this->getRequest()->getParams();
if($params['field'] == 'taxvat'){
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if($validacao == false){
$resultTaxvat = array(
"response" => "Taxvat is not valid",
"field" => $params['field']
);
}
$this->getResponse()->setBody(json_encode($resultTaxvat));
}
if($params['field'] = 'email_address'){
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
$resultEmail = array(
"response" => $validacaoEmail, //Type a valid Email
"field" => $params['field']
);
$this->getResponse()->setBody(json_encode($resultEmail));
}
}
问题是什么:
我总是只得到第二个“如果”的电子邮件回复。 欢迎任何帮助。
干杯
答案 0 :(得分:1)
你的第二个IF语句是传递一个值而不是比较......我认为你应该写if ($params['field'] === 'email_address')
关于您的问题,请尝试以下方法:
public function validarAction()
{
$params = $this->getRequest()->getParams();
$error = false;
$errors = [];
if ($params['field'] == 'taxvat') {
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if (!$validacao) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Taxvat is not valid',
];
}
}
if ($params['field'] === 'email_address') {
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
if (!$$validacaoEmail) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Type a valid Email',
];
}
}
$this->getResponse()->setBody(json_encode([
'error' => $error,
'errors' => $errors
]));
}
... tyr使用循环结构来重构这个。因为如果要验证很多字段,这可能会导致很多IF语句。
编辑:
已将$result
更改为$errors
,将JSON索引status
更改为error
。使用JS上的更新代码进行迭代会更容易。