提交前验证表单字段 [英] Validating form fields before submit

查看:71
本文介绍了提交前验证表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有来自 frmvalidator 的此功能,该功能用于比较两个输入字段.问题是我有两个必填字段,用户需要填写一个或两个字段,但不能不填写两个输入.

I have this function from frmvalidator which I am using to compare two input fields. The thing is I got 2 fields that are required and the user need to fill one or both but can not leave the two input unfilled.

这是我一直在努力的事情:

Here is my what I've been working on:

<form id="contact_form" action="contact.php" method="POST">
  <label>RFC ** </label>
  <input class="fiscal-input" type="text" name="rfc" placeholder="">
  <label> ó CURP **</label>
  <input class="fiscal-input" type="text" name="curp" placeholder="">
</form>

frmvalidator.addValidation("curp","regexp=^[A-Z]{1}[AEIOU]{1}[A-Z]{2}[0-9]{2}(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])[HM]{1}(AS|BC|BS|CC|CS|CH|CL|CM|DF|DG|GT|GR|HG|JC|MC|MN|MS|NT|NL|OC|PL|QT|QR|SP|SL|SR|TC|TS|TL|VZ|YN|ZS|NE)[B-DF-HJ-NP-TV-Z]{3}[0-9A-Z]{1}[0-9]{1}$","Por favor ingrese un CURP válido.");
frmvalidator.addValidation("rfc","regexp=^([A-Z,Ñ,&]{3,4}([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])[A-Z|\d]{3})$","Por favor ingrese un CURP válido.");

两个正则表达式仅将输入控制为某些字母数字. 我需要的是一个javascript函数,该函数可以填充一个或两个,但不能将其填充为空.

The two regex just control the input to be certain alphanumeric digits. What I need is a javascript function which allows to fill one or both but no to keep them empty.

你们可以用这个指导我吗?

Can you guys guide me with this?

推荐答案

您可以使用简单的表单提交处理程序进行自定义验证.我在下面发布示例代码.

You can use a simple form submit handler to do the custom validation. I am posting an example code below.

document.getElementById( 'contact_form' ).addEventListener('submit', function(e) {
  var fields = document.querySelectorAll( '#contact_form .fiscal-input');
  var value = '';
  for( var i=0, len = fields.length; i<len; i++ ) {
    value = value || fields[i].value;
  }
  if(!value) {
    e.preventDefault();
  }
});

这篇关于提交前验证表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆