Custom Validation Message without Submitting Form

Custom Validation
Follow us

This article is a solution if you want to set a custom validation message without submitting a form, and if you are in a situation where you just want to submit the particular fields using ajax but Don’t know how to VALIDATE your form with a custom message.

We see that validating the HTML forms without submit event is a frequent requirement of the development team. HTML provides the special “required” attribute which prevents the form of submission on invalid input. With this feature, we get to see the default validation message like “Please fill in this field”. Often we want to show our custom validation message on validation but don’t want to submit a form.

Well you can achieve this using oninput=”this.setCustomValidity(”)” & oninvalid=”this.setCustomValidity(‘Your Custom Message’)”.

This “this.setCustomValidity()” javascript sets the custom message. But it will become glitchy for your application.

Putting these above attributes your code will be lengthened and it would not be a feasible solution when it comes to the huge requirement of the input fields. For this, we would need to implement our own custom function to work with.

Don’t worry! We have come up with the solution. I’ve implemented a function your custom message is set, just pass the form ID and it will ease your work.

HTML FORM:
<form id="resetPassword" action="#">
		<div class="form-group">
			<label class="form-label">
				Old password
			</label>
			<input type="password" id="opasswd" placeholder="Password " data-invalid-message="Please enter old password" required="">
		</div>
		<div class="form-group">
			<label class="form-label">
				New password
			</label>
			<span>
				<input type="password"id="tpasswd" placeholder="Password" data-invalid-message="Please enter new password "
                       pattern="^(?=.*?[0-9])(?=.*?[~.#?!@$%^&amp;*+_=,/:;-|\x22]).{8,16}$" required="">
			</span>
		</div>
		<div class="form-group">
			<label class="form-label">
				Confirm new password
			</label>
			<input type="password" id="tcpasswd" placeholder="Confirm Password" data-invalid-message="Please confirm new password " required="">
		</div>
		<div class="form-group">
			<input type="button" id="resetPasswordFormId" value="Set Password ">
		</div>
</form>

In the above HTML form, the data-invalid-message attribute is added where your custom message is set by your jquery function.

JQUERY FUNCTION:
function customValidationMessage(formid) {
	$('#'+formid).find('input').each(function () {
		$(this).on('invalid', function() {
			var messg = ($(this).data('invalidMessage'));
			this.setCustomValidity(messg);
		});
		$(this).on('input select', function() {
			this.setCustomValidity('');
		});
	});
}

On invalid, the validation message is set and on valid it is set to null.