I am currently working on validating a field with the following requirements:
- No validation when the user first lands on the page
- Validation triggers when the user clicks on the Name Query field, and it validates on both key up and focus out events
- The field is also validated on form submission: if the field is invalid, clicking the submit button should display the validation message without submitting the form; the form will only be submitted when the field is valid
Below is the code snippet I have developed:
var myForm = $("#myform"),
nameQuery = $("#NameQuery");
myForm.validate({
rules: {
NameQuery: "required"
},
messages: {
NameQuery: "Please fill in name query"
}
});
nameQuery.on("focusout keyup submit", function() {
var isValid = myForm.valid();
if (!isValid) {
nameQuery.addClass("alert-text");
}
else {
nameQuery.removeClass("alert-text");
};
});
nameQuery.on("submit", function() {
var isValid = myForm.valid();
if (isValid) {
$("p").html("Form submitted");
}
else {
$("p").empty();
};
});
.alert-text {
border: 1px dashed red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="myform" method="post">
<label for="NameQuery">Name Query: </label>
<input type="text" id="NameQuery" name="NameQuery">
<input type="submit" value="Search">
<p></p>
</form>
There are a few issues to address:
- Using
var isValid = myForm.valid();
twice seems redundant. Can this be optimized? - When the field is valid, clicking the submit button causes everything to disappear. This behavior needs to be corrected
- Are there any enhancements that can be made to improve the snippet?
EDIT: When mentioning code repetition and the need for conciseness, I am looking for a way to merge these two parts into one unified section:
nameQuery.on("focusout keyup submit", function() {
var isValid = myForm.valid();
if (!isValid) {
nameQuery.addClass("alert-text");
}
else {
nameQuery.removeClass("alert-text");
};
});
And
nameQuery.on("submit", function() {
var isValid = myForm.valid();
if (isValid) {
$("p").html("Form submitted");
}
else {
$("p").empty();
};
});
Both segments target the same element and share a similar logic.