I use JavaScript to validate my form but the JavaScript can only validate a field at a time which means I have to duplicate the JavaScript for every field that I want to validate.
For Example,
My form has the Phone and Email fields that I want to validate, To achieve that, I had to write the javascript with the phone ID separately and write the javascript with the email ID separately.
Is it possible to validate the phone and email fields independently but with one javascript file and different ids?
My Sample code is below;
<!--THIS SCRIPT ONLY VALIDATES THE PHONE FIELD -->
<!--TO VALIDATE THE EMAIL FIELD, I HAVE TO DUPLICATE THIS SCRIPT AND CHANGE THE IDS TO email -->
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isphoneInUse(value)) {
alert ("Phone In Use!\nPlease provide another one");
$(".validate").hide();
} else {
$(".validate").show();
}
});
$('#submitForm()').on('submit', function(e) {
var value = $("#phone").val();
if (isphoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return 0;
}
})
function isphoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" runat="server" >
<div class="validate" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Phone Available ✓</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<br/><br/>
<div class="validate2" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Email Available ✓</b></span></div>
<input type="email" name='email' required='' id="email" placeholder="hello@youremail.com"/>
</div>
<br/><br>
<button class="button" id="submitForm" type="submit" value=""><span>Check </span></button>
</form>