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.");
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();
}
});
This is a pretty simple validation problem in my opinion.
I've called a validation function on clicking the submit button. You may alternatively call this onblur.
<form id="contact_form" onsubmit="return validate();" action="contact.php" method="POST">
In the validation function,the following is done
validate=function(){
alert("called");
x=document.getElementById("rfc").value;
y=document.getElementById("curp").value;
if(x==""&&y=="")
return false;
else
{
alert(x);
alert(y);
//Call your validation function here
return true;
}}
Here is a DEMO
As you asked you want to validate form fields before form submit you can just do the following
// fires every time this field changes
$('your_selector_of_element').on('change', function() {
$(this).valid(); // force a validation test on this field
});
This will force the validation on element before form is submitted and you will get the validation message.