JSFiddle - React, Tailwind, and code Playground
by arackaf
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<form>
fname <input type="text" maxlength="50" name="firstName" /> <br>
lname <input type="text" maxlength="50" name="lastName" /> <br>
(<input style="width:30px;" type="text" class="phone" name="phone-3ha" />)
<input style="width:30px;" type="text" class="phone" name="phone-3hb" />-
<input style="width:40px;" type="text" class="phone" name="phone-4h" />
</form>
<button>Submit</button>
JavaScript
$(function(){
var contactForm = $("form");
$.validator.addMethod("homeGood", function(value, elem, args) {
return allGood($(elem).closest("form"), "h");
}, "");
function allGood(currentForm, phoneVal){
var p3a = $(currentForm).find("input[name='phone-3" + phoneVal + "a']");
var p3b = $(currentForm).find("input[name='phone-3" + phoneVal + "b']");
var p4 = $(currentForm).find("input[name='phone-4" + phoneVal + "']");
if (!p3a.val() && !p3b.val() && !p4.val()){
return true;
}
return p3a.val().length === 3 && p3b.val().length === 3 && p4.val().length === 4;
}
contactForm.validate({
rules: {
'firstName': { required: true },
'lastName': { required: true },
'phone-3ha': { rangelength: [3, 3], homeGood: '' },
'phone-3hb': { rangelength: [3, 3], homeGood: '' },
'phone-4h': { rangelength: [4, 4], homeGood: '' }
}, messages: {
'firstName': { required: 'First name required' },
'lastName': { required: 'Last name required' },
'phone-3ha': '3 digits' ,
'phone-3hb': '3 digits' ,
'phone-4h': { rangelength: '4 digits', homeGood: 'Home phone not fully filled out' }
}
});
$(".phone").validate({
onfocusout: false,
onkeyup: false,
onkeydown: false
});
$("button").click(function(){
contactForm.valid();
})
});