function validatePhone(phone) { // Remove all non-digit characters var cleaned = phone.replace(/\D/g, ''); var valid = cleaned.length == 10; if (!valid) { return false; } else { return true; } } $().ready(function() { $("body").on("click touchstart touch", ".trybefore-button", function () { var name = $.trim($("#name").val()); var phone = $.trim($("#phone").val()); // Clear any previous error highlights $("#name, #phone").removeClass("error"); if (!name.length) { $("#name").addClass("error"); $("#name").focus(); } else if (validatePhone(phone)) { $('form#trybefore').submit(); } else { $("#phone").addClass("error"); $("#phone").val(''); $("#phone").focus(); } }); $("#search_go").click(function() { $("#sitesearch").submit(); }); });