Note: Above answers are all correct and perfect with simple explanation, but in case if you want to show an actual error message to the user, (In case you want to a complex validation), then below answer is for you,
Here In my scenario I have two checkbox in my form, and I want to validate that at least one checkbox should be clicked, if not then I will show a error message to the user.
<%= form_tag( add_to_telegram_path, method: :post, id: 'add-to-telegram-form') do |t| %>
Select channel
<%= check_box_tag "channel_names[]", id: 'channel_1'%> Channel 1
<%= check_box_tag "channel_names[]", id: 'channel_2'%> Channel 2
<%= button_tag "Send", :class => 'btn btn-success', id: 'add-to-telegram-btn', onclick: "validTelegram()" %>
<%end%>
Then in JS,
function validTelegram() {
event.preventDefault();
var checkboxes = Array.from(document.getElementsByName("channel_names[]"));
if(checkboxes.reduce((acc, curr) => acc || curr.checked, false)){
$('#add-to-telegram-form').submit();
} else {
//swal('Error','Please select atleast one channel!','warning');
alert('Some error!')
}
}
- I called a JS function on the submit click of
form_tag
, (If you are using sibmit_tag
replace it with button_tag
)
- I have prevented default behaviour of the submit button
- Then I started to get the elements by its Id/Class or by Name, and checked what ever I want to do in the JS, and then based on my validation Either I am calling submit() on the form ID, or showing the error message.
Note: For showing error message I have used Sweet alert, you can stick with the alert();, but in case If you are looking for better UI, then uncomment my swal() code in JS and comment out alert();
You can read more about Sweet Alert PopUp