Hi can I ask some help how you validate form required using jquery without using framework validation
and without repeating code I mean more dynamic .
I have this code when submitting the form but I don’t like the way I coded it. I just Imagine what if I have long form, then my code will also gets long.
var category = $("[name='category']").val();
var type = $("[name='type']").val();
if(category == ''){
//show inline message error
}
if(type== ''){
//show inline message error
}
Hi @jemz, there are no required attributes on any input elements… but if you add some you might do something like this:
$('form').on('submit', function (event) {
$('[required]', event.target).each(function (index, element) {
// If the field has a value, do nothing
if (element.value) {
return
}
// Otherwise prevent the form submission
event.preventDefault()
// Show error message here
})
})
You’d also have to add the novalidate attribute to the form to disable the native browser validation; have a look here for a good guide to custom form validation:
Hi thank you for the quick reply…so this is the other way to validate if the user will not input to the field then submit the form. By the way do we need to use required instead of checking empty field?..also is this possible to use the button on click then validate form?
Because the HTML5 required attribute is there, you don’t need to use JavaScript at all. The web browser does all of the validation for you.
When you use HTML5 validation techniques, the web browser validates the form fields as you interact with them. You don’t have to wait until the submit occurs.
Not sure what you mean, in my above example I am checking if any field with a required attribute has an empty value “manually” (as opposed to using the native form validation, which should disable first then). You might also use some other attribute (say a required class) and query for that, but semantically and in terms of accessibility it would make sense to use the attribute intended for it.
Above we are simply listening to a form submit event, whatever causing it; you can as well listen to button click events, but then the form will not get validated if the user just presses enter, for example.