In rails form, I want to validate as "Should not enter space in starting of text field". That is no space comes in the beginning of the text field. Space value should not be as first character. Is there any validation in rails? or can be done by using javascript? Thanks in advance.
-
Useful link to start with http://stackoverflow.com/questions/2308134/trim-in-javascript-not-working-in-ie – claudios Jan 23 '17 at 05:12
1 Answers
I'll be referring to the exact field you are validating as fieldx; replace with whatever the field relates to in your case.
If you're saving the results of the form to a record in your database via rails ActiveRecord, I recommend doing this validation on the model level, an example might be:
validates_format_of :fieldx, :with => /^[^\s].*$/
If you only want to validate the form field client side (in the form itself) I recommend HTML5 pattern validations. If you aren't using a template language or form helper, it would look like this:
<input type="text" title="fieldx" id="fieldx" name="fieldx" pattern="^[^\s].*$">
If you are using Rails form helper, this would be:
f.text :fieldx, id: 'fieldx', pattern: /^[^\s].*$/
The ^[^\s].*$
part is a regular expression as you may know. The regex you may want to use might just be ^\S+
. I'd recommend this tool for testing your regexes so that you can get what works best in your specific case:
http://rubular.com/

- 1,071
- 12
- 17
-
You'll have to handle the error response from the server in the case of doing a model validation, which may involve more work. However it is the best way to ensure records are not saved with the invalid format (leading whitespace) because records created via terminal, etc will also be validated. – quetzaluz Jan 23 '17 at 05:12
-
3thanks @quetzaluz ur [link](http://rubular.com/) helps me to find the regex pattern. And I done validation through script livevalidation with the pattern as **pattern: /^\S/** – Jan 23 '17 at 06:08