Using the form_with method I made a form to input a numerical value in form.number_field. If you enter the correct number, no error will occur, and if you try to enter a number that exceeds the validation, an error will occur at that timing. However, if you send the input form empty,
Please enter ○○ ○○ is an invalid value ○○ is not in the list
And I get 3 errors. Just send the sky and you don't need three! !! !!
model
with_options presence: true do
validates :grade, format: { with: /\A[0-9]+\z/, allow_blank: true}, inclusion: { in: 1..7, allow_blank: true }
validates :class_number, format: { with: /\A[0-9]+\z/, allow_blank: true }, inclusion: { in: 1..10, allow_blank: true }
end
format is regular expression validation. inclusion is the validation of the numerical range.
allow_blank: true
is a method that does not perform validation if the value is empty.
It's verbose, but when it's empty, format and inclusion validation doesn't respond.
Looking at the error message again, "○○ is an invalid value" is responding to format It can be seen that "○○ is not in the list" is responding to inclusion.
If you use a foreign key and validate it with presence: true
, you will get two error messages with similar content.
Delete the validation of the foreign key described in the model.
The order can be resolved by changing the description position of validation and association. I am grateful that no particular problem will occur because I only change the position of the description. This is probably because the code is being read from above. It's a little bit, but I want to send an error message in the order of the input form.
Recommended Posts